Skip to main content

mq_lang/
engine.rs

1use std::path::PathBuf;
2
3mod compiled_program;
4#[cfg(feature = "debugger")]
5mod debugger;
6mod session;
7
8pub use compiled_program::CompiledProgram;
9pub(crate) use compiled_program::ProgramBody;
10#[cfg(not(feature = "debugger"))]
11pub(crate) use compiled_program::VmCache;
12pub use session::Session;
13
14#[cfg(feature = "debugger")]
15use crate::Source;
16use crate::io::{Io, NativeIo, SandboxedIo};
17use crate::tarn::{self, SessionBindings};
18use crate::{
19    ArenaId, Ident, ModuleResolver, MqResult, Range, RuntimeValue, RuntimeValues, Shared, SharedCell, TokenKind,
20    layered_token_arena, module::resolver::DefaultModuleResolver, token_alloc,
21};
22
23use crate::{
24    ModuleLoader, Token, TokenArena,
25    arena::Arena,
26    error::{self},
27    parse, parse_with_prelude,
28    runtime::builtin::io_context,
29};
30
31/// An error returned when a value cannot be added to an [`Engine`] environment.
32#[derive(Debug, thiserror::Error, PartialEq, Eq)]
33pub enum DefineValueError {
34    /// The value contains execution state that belongs to a particular VM.
35    #[error("cannot define a VM-bound {0}")]
36    VmBoundValue(&'static str),
37}
38
39/// The main execution engine for the mq.
40///
41/// The `Engine` manages parsing and evaluation of mq code.
42/// It provides methods for configuration, loading modules, and evaluating code.
43///
44/// # Examples
45///
46/// ```rust
47/// use mq_lang::DefaultEngine;
48///
49/// let mut engine = DefaultEngine::default();
50/// engine.load_builtin_module();
51///
52/// let input = mq_lang::parse_text_input("hello").unwrap();
53/// let result = engine.eval("add(\" world\")", input.into_iter());
54/// assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());
55/// ```
56#[derive(Debug, Clone)]
57pub struct Engine<T: ModuleResolver = DefaultModuleResolver, IO: Io = SandboxedIo<NativeIo>> {
58    /// VM state: see [`tarn::VmState`].
59    pub(crate) vm: tarn::VmState<T, IO>,
60    pub(crate) token_arena: Shared<SharedCell<Arena<Token>>>,
61    pub(crate) vm_module_prelude: Vec<VmModulePrelude>,
62    /// Loaded `.mqc` programs, keyed by checksum.
63    #[cfg(feature = "mqc")]
64    pub(crate) mqc_programs: rustc_hash::FxHashMap<[u8; crate::mqc::CHECKSUM_LEN], CompiledProgram>,
65    /// Declared last, so it is dropped, and collects, after the VM state and the variables it holds.
66    cycles: tarn::CycleCandidates,
67}
68
69/// A module explicitly prepared through the Engine API, replayed before VM compilation.
70/// The VM needs their AST declarations present while it statically resolves the user's query.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub(crate) enum VmModulePrelude {
73    Include(String),
74    /// Module name and optional `as` alias.
75    Import(String, Option<String>),
76}
77
78fn create_default_token_arena() -> Shared<SharedCell<Arena<Token>>> {
79    let token_arena = Shared::new(SharedCell::new(Arena::new(1)));
80    token_alloc(
81        &token_arena,
82        Token {
83            // Ensure at least one token for ArenaId::new(0)
84            kind: TokenKind::Eof, // Dummy token
85            range: Range::default(),
86            module_id: ArenaId::new(0), // Dummy module_id
87        },
88    );
89    token_arena
90}
91
92impl<T: ModuleResolver> Default for Engine<T, SandboxedIo<NativeIo>> {
93    fn default() -> Self {
94        Self::new(T::default())
95    }
96}
97
98// `new` is pinned to the default `IO` (rather than generic over any `IO: Default`) because Rust
99// doesn't use a generic parameter's default as an inference fallback; callers like
100// `Engine::new(resolver)` have no other way to pin `IO`. Mirrors the `HashMap::new`/
101// `HashMap::with_hasher` split. To use a different `IO`, annotate the binding's type, e.g.
102// `let engine: Engine<T, MyIo> = Engine::new(resolver);` (this only fixes the *value* passed at
103// construction; use `set_io` afterwards to install it).
104impl<T: ModuleResolver> Engine<T, SandboxedIo<NativeIo>> {
105    /// Creates an engine with the given module resolver and a sandboxed native `Io` that denies all access by default.
106    pub fn new(module_resolver: T) -> Self {
107        let token_arena = create_default_token_arena();
108        let module_loader = ModuleLoader::new(module_resolver);
109        Self {
110            vm: tarn::VmState::with_module_loader(module_loader),
111            token_arena,
112            vm_module_prelude: Vec::new(),
113            #[cfg(feature = "mqc")]
114            mqc_programs: Default::default(),
115            cycles: Default::default(),
116        }
117    }
118}
119
120impl<IO: Io> Engine<DefaultModuleResolver, IO> {
121    /// Creates an engine with the default module resolver and a shared [`Io`].
122    ///
123    /// The same `io` handles builtins and local `include`/`import` statements, so
124    /// filesystem access follows one permission policy. Standard modules remain available.
125    /// Use [`Engine::with_io`] when supplying a custom module resolver.
126    ///
127    /// # Examples
128    ///
129    /// ```rust
130    /// use mq_lang::{Engine, NativeIo, SandboxedIo, Shared};
131    ///
132    /// let io = Shared::new(SandboxedIo::new(NativeIo::default()));
133    /// let mut engine = Engine::with_default_io(io);
134    /// engine.load_builtin_module();
135    /// ```
136    pub fn with_default_io(io: Shared<IO>) -> Self {
137        let resolver = DefaultModuleResolver::with_io(Shared::clone(&io) as Shared<dyn Io>, vec![]);
138        Self::with_io(resolver, io)
139    }
140}
141
142impl<T: ModuleResolver, Inner: Io> Engine<T, SandboxedIo<Inner>> {
143    /// Whether any environment-variable access is granted (fully or restricted to an allowlist).
144    pub fn is_env_allowed(&self) -> bool {
145        self.vm.io.is_env_allowed()
146    }
147}
148
149impl<T: ModuleResolver, IO: Io> Engine<T, IO> {
150    /// Like the [`SandboxedIo<NativeIo>`]-pinned [`Engine::new`], but generic over `IO` and
151    /// takes the [`Io`] value up front, for hosts that need to select the `Io` *type* at
152    /// construction time, not just its value via [`set_io`](Self::set_io). Useful for e.g. a
153    /// test runner that wants an in-memory mock `Io` installed from the start.
154    ///
155    /// This only wires the evaluator side (builtins); pass the same `io` to
156    /// [`DefaultModuleResolver::with_io`] when constructing the resolver so local-filesystem
157    /// module resolution is gated consistently.
158    pub fn with_io(module_resolver: T, io: Shared<IO>) -> Self {
159        let token_arena = create_default_token_arena();
160        let module_loader = ModuleLoader::new(module_resolver);
161        Self {
162            vm: tarn::VmState::with_module_loader_and_io(module_loader, io),
163            token_arena,
164            vm_module_prelude: Vec::new(),
165            #[cfg(feature = "mqc")]
166            mqc_programs: Default::default(),
167            cycles: Default::default(),
168        }
169    }
170
171    /// Set the maximum call stack depth for function calls.
172    ///
173    /// This prevents infinite recursion by limiting how deep function
174    /// calls can be nested. Useful for controlling resource usage. The default is 100,000 in
175    /// release builds (256 in debug builds).
176    pub fn set_max_call_stack_depth(&mut self, max_call_stack_depth: u32) {
177        self.vm.options.max_call_stack_depth = max_call_stack_depth;
178    }
179
180    /// Set the maximum wall-clock duration allowed for a single `eval` call.
181    ///
182    /// Disabled by default (no timeout); pass `None` to disable it again. When exceeded,
183    /// evaluation stops with `RuntimeError::Timeout`; the deadline is checked periodically
184    /// inside loops and function calls, so it may be exceeded slightly before evaluation
185    /// actually stops.
186    pub fn set_timeout(&mut self, timeout: impl Into<Option<std::time::Duration>>) {
187        self.vm.options.timeout = timeout.into();
188    }
189
190    /// Enables traces for uncaught VM errors.
191    pub fn set_capture_stack_trace(&mut self, enabled: bool) {
192        self.vm.options.capture_stack_trace = enabled;
193    }
194
195    /// Sets the [`Io`] this engine uses for file, environment-variable, and network
196    /// access: both for builtins (`read_file`, `write_file`, `http`, ...) and for
197    /// local module resolution (`include`/`import`). Defaults to an all-denied
198    /// [`SandboxedIo`](crate::SandboxedIo) wrapping [`NativeIo`](crate::NativeIo),
199    /// so a host must opt in explicitly.
200    ///
201    /// This only affects the evaluator side (builtins); pass the same `io` to
202    /// [`DefaultModuleResolver::with_io`] when constructing the resolver so
203    /// local-filesystem module resolution is gated consistently.
204    pub fn set_io(&mut self, io: Shared<IO>) {
205        self.vm.io = Shared::clone(&io);
206    }
207
208    /// Set search paths for module loading.
209    ///
210    /// These paths will be searched when loading external modules
211    /// via the `include` statement in mq code.
212    pub fn set_search_paths(&mut self, paths: Vec<PathBuf>) {
213        self.vm.module_loader.set_search_paths(paths);
214        #[cfg(not(feature = "debugger"))]
215        self.vm.invalidate_module_cache();
216    }
217
218    /// Define a string variable that can be used in mq code.
219    ///
220    /// This allows you to inject values from the host environment
221    /// into the mq execution context.
222    pub fn define_string_value(&self, name: &str, value: &str) {
223        self.define_value_unchecked(name, RuntimeValue::String(Shared::new(value.to_string())));
224    }
225
226    /// Defines several string variables and publishes one VM global snapshot.
227    ///
228    /// Useful when updating related values, such as the file path variables for each input.
229    ///
230    /// ```
231    /// let engine = mq_lang::DefaultEngine::default();
232    /// engine.define_string_values(&[("__FILE__", "input.md"), ("__FILE_NAME__", "input.md")]);
233    /// ```
234    pub fn define_string_values(&self, values: &[(&str, &str)]) {
235        self.vm.define_many(values.iter().map(|(name, value)| {
236            (
237                Ident::new(name),
238                RuntimeValue::String(Shared::new((*value).to_string())),
239            )
240        }));
241    }
242
243    /// Defines an arbitrary runtime value in the current environment.
244    ///
245    /// Values that retain VM execution state, such as coroutines and closures, cannot be
246    /// injected. They may contain bytecode and source locations owned by another evaluation.
247    pub fn define_value(&self, name: &str, value: RuntimeValue) -> Result<(), DefineValueError> {
248        if let Some(kind) = value.vm_bound_value_kind() {
249            return Err(DefineValueError::VmBoundValue(kind));
250        }
251        self.define_value_unchecked(name, value);
252        Ok(())
253    }
254
255    fn define_value_unchecked(&self, name: &str, value: RuntimeValue) {
256        self.vm.define(Ident::new(name), value);
257    }
258
259    /// Registers a native Rust function under `name`, callable from mq code as `name(...)`.
260    ///
261    /// Accepts two forms:
262    ///
263    /// - A raw form taking the already-evaluated call arguments as a slice and returning a
264    ///   single [`RuntimeValue`]: `|args: &[RuntimeValue]| -> HostFnResult { .. }`.
265    /// - A typed form taking up to eight plain Rust arguments (any combination of `i64`, `f64`,
266    ///   `String`, `bool`, `RuntimeValue`, `Vec<T>`, or `Option<T>` for a [`ValueAdapter`](crate::ValueAdapter) `T`),
267    ///   returning `Result<R, HostFunctionError>` for an `R: ValueAdapter`. Argument and return
268    ///   values are converted to/from `RuntimeValue` automatically; a wrong argument count or
269    ///   type is reported as a [`HostFunctionError`](crate::HostFunctionError) rather than panicking.
270    ///
271    /// Errors and panics raised by the function are caught at the call boundary and surfaced as
272    /// a normal mq runtime error rather than aborting evaluation or unwinding through the
273    /// evaluator; recursion depth and the configured timeout ([`Self::set_timeout`]) are
274    /// enforced around each call exactly as for a user-defined function call.
275    ///
276    /// A registered function only fills in a name that would otherwise be undefined: a `def` of
277    /// the same name always takes precedence, and so does *any* built-in function name, whether
278    /// or not [`Self::load_builtin_module`] was called: name resolution itself falls back to
279    /// the built-in table before host functions are ever consulted. Host functions therefore
280    /// extend the set of callable names rather than override existing ones; pick a name that
281    /// doesn't collide with a builtin.
282    ///
283    /// # Examples
284    ///
285    /// ```rust
286    /// use mq_lang::{DefaultEngine, HostFunctionError, RuntimeValue, Shared};
287    ///
288    /// let mut engine = DefaultEngine::default();
289    /// engine.load_builtin_module();
290    ///
291    /// // Raw form: works with any number of arguments, matched by hand.
292    /// engine.register_fn("shout", |args: &[RuntimeValue]| match args {
293    ///     [RuntimeValue::String(s)] => Ok(RuntimeValue::String(Shared::new(format!("{}!", s.to_uppercase())))),
294    ///     _ => Err(HostFunctionError::new("shout() expects one string argument")),
295    /// });
296    ///
297    /// // Typed form: argument and return conversions are handled for you.
298    /// engine.register_fn("double", |n: i64| Ok(n * 2));
299    ///
300    /// let input = mq_lang::parse_text_input("hello").unwrap();
301    /// let result = engine.eval(r#"shout("hi") + to_string(double(21))"#, input.into_iter());
302    /// assert_eq!(result.unwrap(), vec!["HI!42".to_string().into()].into());
303    /// ```
304    pub fn register_fn<F, Marker>(&self, name: impl Into<crate::Ident>, f: F)
305    where
306        F: crate::runtime::host::IntoHostFunction<Marker>,
307    {
308        let name = name.into();
309        let f = f.into_host_fn();
310        #[cfg(not(feature = "sync"))]
311        self.vm.host_functions.borrow_mut().insert_shared(name, f);
312        #[cfg(feature = "sync")]
313        self.vm.host_functions.write().unwrap().insert_shared(name, f);
314    }
315
316    /// Load the built-in function modules.
317    ///
318    /// This must be called to enable access to standard functions
319    /// like `add`, `sub`, `map`, `filter`, etc.
320    pub fn load_builtin_module(&mut self) {
321        self.vm.load_builtin_module(Shared::clone(&self.token_arena));
322    }
323
324    /// Import an external module by name.
325    ///
326    /// The module will be searched for in the configured search paths
327    /// and made available for use in mq code.
328    pub fn import_module(&mut self, module_name: &str) -> Result<(), Box<error::Error>> {
329        self.vm
330            .module_loader
331            .load_from_file(module_name, Shared::clone(&self.token_arena))
332            .map_err(|e| Box::new(error::Error::from_error("", e.into(), self.vm.module_loader.clone())))?;
333        self.vm_module_prelude
334            .push(VmModulePrelude::Import(module_name.to_string(), None));
335        Ok(())
336    }
337
338    /// Load an external module by name.
339    ///
340    /// The module will be searched for in the configured search paths
341    /// and made available for use in mq code.
342    pub fn load_module(&mut self, module_name: &str) -> Result<(), Box<error::Error>> {
343        self.vm
344            .module_loader
345            .load_from_file(module_name, Shared::clone(&self.token_arena))
346            .map_err(|e| Box::new(error::Error::from_error("", e.into(), self.vm.module_loader.clone())))?;
347        self.vm_module_prelude
348            .push(VmModulePrelude::Include(module_name.to_string()));
349        Ok(())
350    }
351
352    /// The main engine for evaluating mq code.
353    ///
354    /// The `Engine` manages parsing and evaluation of mq.
355    /// It provides methods for configuration, loading modules, and evaluating code.
356    ///
357    /// # Examples
358    ///
359    /// ```
360    /// let mut engine = mq_lang::DefaultEngine::default();
361    /// engine.load_builtin_module();
362    ///
363    /// let input = mq_lang::parse_text_input("hello").unwrap();
364    /// let result = engine.eval("add(\" world\")", input.into_iter());
365    /// assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());
366    /// ```
367    ///
368    pub fn eval<I: Iterator<Item = RuntimeValue>>(&mut self, code: &str, input: I) -> MqResult {
369        if code.is_empty() {
370            return Ok(vec![].into());
371        }
372
373        // Scoped before `parse`, not just `eval_compiled_vm`, so bare `$VAR` resolution sees this engine's `Io`.
374        let _io_guard = io_context::scoped(Shared::clone(&self.vm.io) as Shared<dyn Io>);
375        let token_arena = self.query_token_arena();
376        let program = parse(code, Shared::clone(&token_arena))?;
377
378        #[cfg(feature = "debugger")]
379        self.vm.module_loader.set_source_code(code.to_string());
380
381        let compiled = CompiledProgram::cached(code.to_string(), program);
382        self.run_compiled(&compiled, input, token_arena, None)
383            .map_err(|cause| Box::new(error::Error::from_error(code, cause, self.vm.module_loader.clone())))
384    }
385
386    /// Compiles mq code into a [`CompiledProgram`] that can be evaluated multiple times.
387    ///
388    /// Use this with `eval_compiled` to avoid re-parsing the same query for each input.
389    pub fn compile(&mut self, code: &str) -> Result<CompiledProgram, Box<error::Error>> {
390        self.compile_with_prelude("", code)
391    }
392
393    /// Like [`Self::compile`], running `prelude` before `code`.
394    ///
395    /// Diagnostics show only `code`, so a prelude the caller adds on the user's behalf
396    /// never appears in error output or shifts its positions.
397    #[doc(hidden)]
398    pub fn compile_with_prelude(&mut self, prelude: &str, code: &str) -> Result<CompiledProgram, Box<error::Error>> {
399        if prelude.is_empty() && code.is_empty() {
400            return Ok(CompiledProgram::cached(String::new(), crate::Program::new()));
401        }
402        let _io_guard = io_context::scoped(Shared::clone(&self.vm.io) as Shared<dyn Io>);
403        let program = parse_with_prelude(prelude, code, Shared::clone(&self.token_arena))?;
404        Ok(CompiledProgram::cached(code.to_string(), program))
405    }
406
407    /// Evaluates a pre-compiled program against the given input.
408    ///
409    /// Use with `compile` to avoid re-parsing the same query for each input file,
410    /// or with a [`CompiledProgram`] constructed from a deserialized JSON AST (`ast-json` feature).
411    ///
412    /// # Examples
413    ///
414    /// ```rust
415    /// let mut engine = mq_lang::DefaultEngine::default();
416    /// engine.load_builtin_module();
417    ///
418    /// let compiled = engine.compile("add(\" world\")").unwrap();
419    /// let input = mq_lang::parse_text_input("hello").unwrap();
420    /// let result = engine.eval_compiled(&compiled, input.into_iter());
421    /// assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());
422    /// ```
423    pub fn eval_compiled<I: Iterator<Item = RuntimeValue>>(
424        &mut self,
425        compiled: &CompiledProgram,
426        input: I,
427    ) -> MqResult {
428        #[cfg(feature = "debugger")]
429        self.vm.module_loader.set_source_code(compiled.source.clone());
430
431        self.eval_compiled_vm(compiled, input)
432    }
433
434    /// Lists the Tarn bytecode that would be executed for `compiled`, without running it.
435    ///
436    /// Available only with the `debug-trace` feature, for tools such as `mq-dbg`.
437    #[cfg(feature = "debug-trace")]
438    pub fn dump_bytecode(&mut self, compiled: &CompiledProgram) -> Result<crate::BytecodeDump, Box<error::Error>> {
439        self.vm.module_loader.set_source_code(compiled.source.clone());
440        #[allow(clippy::infallible_destructuring_match)]
441        let program = match &compiled.body {
442            ProgramBody::Ast(program) => program,
443            #[cfg(feature = "mqc")]
444            ProgramBody::Precompiled(precompiled) => {
445                return Ok(tarn::dump_compiled_program(precompiled, &self.token_arena));
446            }
447        };
448        let global_bindings = self.vm.global_bindings_snapshot();
449        let vm_program = tarn::build_program(program, Shared::clone(&self.token_arena), &self.vm_module_prelude)?;
450        let vm_program = vm_program.as_ref().unwrap_or(program);
451
452        tarn::dump_bytecode(
453            vm_program,
454            Shared::clone(&self.token_arena),
455            self.vm.module_loader.with_same_resolver(),
456            &global_bindings,
457        )
458        .map_err(|error| {
459            Box::new(error::Error::from_error(
460                &compiled.source,
461                error.into_inner_error(Shared::clone(&self.token_arena)),
462                self.vm.module_loader.clone(),
463            ))
464        })
465    }
466
467    /// Evaluates one input through the bytecode VM. Same `MqResult` shape as `eval_compiled`.
468    pub(crate) fn eval_compiled_vm<I>(&mut self, compiled: &CompiledProgram, input: I) -> MqResult
469    where
470        I: Iterator<Item = RuntimeValue>,
471    {
472        self.run_compiled(compiled, input, Shared::clone(&self.token_arena), None)
473            .map_err(|cause| {
474                Box::new(error::Error::from_error(
475                    &compiled.source,
476                    cause,
477                    self.vm.module_loader.clone(),
478                ))
479            })
480    }
481
482    /// The arena for one `eval` query's tokens, freed once it has run. A debugger keeps them,
483    /// since it reads them later.
484    fn query_token_arena(&self) -> TokenArena {
485        if cfg!(feature = "debugger") {
486            Shared::clone(&self.token_arena)
487        } else {
488            layered_token_arena(&self.token_arena)
489        }
490    }
491
492    /// Runs `compiled`, resolving its tokens in `token_arena` and carrying `session`'s bindings.
493    pub(crate) fn run_compiled(
494        &mut self,
495        compiled: &CompiledProgram,
496        input: impl Iterator<Item = RuntimeValue>,
497        token_arena: TokenArena,
498        session: Option<&SessionBindings>,
499    ) -> Result<RuntimeValues, error::InnerError> {
500        // Scoped like `eval`/`eval_compiled`, so bare `$VAR` resolution (and anything else
501        // reading the ambient `Io`) inside VM-executed builtins sees this engine's `Io`
502        // rather than whatever the previous scope (or none) left in place.
503        let _io_guard = io_context::scoped(Shared::clone(&self.vm.io) as Shared<dyn Io>);
504
505        #[cfg(feature = "sync")]
506        let host_functions = self.vm.host_functions.read().unwrap().clone();
507        #[cfg(not(feature = "sync"))]
508        let host_functions = self.vm.host_functions.borrow().clone();
509
510        #[cfg(not(feature = "debugger"))]
511        let (global_bindings, environment_key) = self.vm.global_bindings_snapshot_with_key();
512        #[cfg(feature = "debugger")]
513        let global_bindings = self.vm.global_bindings_snapshot();
514
515        #[cfg(feature = "debugger")]
516        let vm_program = compiled
517            .program()
518            .map(|program| tarn::build_program(program, Shared::clone(&token_arena), &self.vm_module_prelude))
519            .transpose()
520            .map_err(|error| error.cause)?
521            .flatten();
522
523        let (timeout, max_call_stack_depth, capture_stack_trace) = (
524            self.vm.options.timeout,
525            self.vm.options.max_call_stack_depth,
526            self.vm.options.capture_stack_trace,
527        );
528        let module_loader = self.vm.module_loader.with_same_resolver();
529
530        let _cycles = self.cycles.enter();
531        let vm = tarn::TarnVm {
532            engine: tarn::EngineRunContext {
533                host_functions: &host_functions,
534                timeout,
535                max_call_stack_depth,
536                capture_stack_trace,
537                token_arena: Shared::clone(&token_arena),
538                module_loader,
539                global_bindings: &global_bindings,
540                session,
541                preresolved_module_vars: Default::default(),
542            },
543            #[cfg(not(feature = "debugger"))]
544            module_prelude: &self.vm_module_prelude,
545            #[cfg(not(feature = "debugger"))]
546            environment_key,
547            #[cfg(not(feature = "debugger"))]
548            module_cache_key: self.vm.module_cache_key,
549            #[cfg(feature = "debugger")]
550            debugger: Shared::clone(&self.vm.debugger),
551            #[cfg(feature = "debugger")]
552            debugger_handler: Shared::clone(&self.vm.debugger_handler),
553            #[cfg(feature = "debugger")]
554            source: Source {
555                name: None,
556                code: compiled.source.clone(),
557            },
558        };
559        vm.run(
560            compiled,
561            #[cfg(feature = "debugger")]
562            vm_program.as_deref(),
563            input,
564        )
565        .map(Into::into)
566        .map_err(|error| error.into_inner_error(token_arena))
567    }
568
569    /// Resolves `module_name` to the path its resolver loaded it from.
570    pub fn get_module_path(&self, module_name: &str) -> Result<String, Box<error::Error>> {
571        let module_loader = &self.vm.module_loader;
572        module_loader
573            .get_module_path(module_name)
574            .map_err(|e| Box::new(error::Error::from_error("", e.into(), module_loader.clone())))
575    }
576
577    /// The mq-lang crate version.
578    pub const fn version() -> &'static str {
579        env!("CARGO_PKG_VERSION")
580    }
581}
582
583#[cfg(feature = "http-import-ureq")]
584impl Engine<DefaultModuleResolver> {
585    /// Replaces the HTTP resolver's domain allowlist.
586    ///
587    /// An empty list restricts access to the built-in default domain
588    /// (`raw.githubusercontent.com/harehare`) only; it does not open up all URLs.
589    pub fn set_http_allowed_domains(&mut self, domains: Vec<String>) {
590        self.vm.module_loader.set_http_allowed_domains(domains);
591        #[cfg(not(feature = "debugger"))]
592        self.vm.invalidate_module_cache();
593    }
594
595    /// Enables or disables HTTP module imports outright, independent of the domain allowlist.
596    ///
597    /// The `mq` CLI calls this with `false` unless `--allow-http-import` is passed, so
598    /// imports are opt-in there; the domain allowlist alone never enables them.
599    pub fn set_http_import_enabled(&mut self, enabled: bool) {
600        self.vm.module_loader.set_http_import_enabled(enabled);
601        #[cfg(not(feature = "debugger"))]
602        self.vm.invalidate_module_cache();
603    }
604
605    /// Clears all locally-cached HTTP module files.
606    ///
607    /// Call this once before processing to force a re-fetch of all cached modules
608    /// on the next resolve (e.g. when `--refresh-modules` is passed on the CLI).
609    pub fn clear_http_cache(&mut self) -> Result<(), crate::module::error::ModuleError> {
610        let result = self.vm.module_loader.clear_http_cache();
611        #[cfg(not(feature = "debugger"))]
612        self.vm.invalidate_module_cache();
613        result
614    }
615
616    /// Clears all HTTP module cache including versioned modules and lock files.
617    ///
618    /// Use this when `--clear-cache` is passed on the CLI to wipe everything.
619    pub fn clear_http_cache_all(&mut self) -> Result<(), crate::module::error::ModuleError> {
620        let result = self.vm.module_loader.clear_http_cache_all();
621        #[cfg(not(feature = "debugger"))]
622        self.vm.invalidate_module_cache();
623        result
624    }
625
626    /// Enables or disables the `mq.lock` integrity check for HTTP imports (on by default).
627    pub fn set_lockfile_enabled(&mut self, enabled: bool) {
628        self.vm.module_loader.set_lockfile_enabled(enabled);
629        #[cfg(not(feature = "debugger"))]
630        self.vm.invalidate_module_cache();
631    }
632
633    /// When `true`, a URL with no existing `mq.lock` entry is a hard error instead of being
634    /// recorded as a new entry (off by default). Mirrors `npm ci` / `cargo build --locked`:
635    /// pass `--frozen` on the CLI so trusting a module's content for the first time
636    /// only ever happens in a reviewable local run, not silently in CI.
637    pub fn set_lockfile_frozen(&mut self, frozen: bool) {
638        self.vm.module_loader.set_lockfile_frozen(frozen);
639        #[cfg(not(feature = "debugger"))]
640        self.vm.invalidate_module_cache();
641    }
642
643    /// Sets the path used for `mq.lock`.
644    pub fn set_lockfile_path(&mut self, path: std::path::PathBuf) {
645        self.vm.module_loader.set_lockfile_path(path);
646        #[cfg(not(feature = "debugger"))]
647        self.vm.invalidate_module_cache();
648    }
649}
650
651#[cfg(test)]
652mod tests;