Skip to main content

Engine

Struct Engine 

Source
pub struct Engine<T: ModuleResolver = DefaultModuleResolver, IO: Io = SandboxedIo<NativeIo>> { /* private fields */ }
Expand description

The main execution engine for the mq.

The Engine manages parsing and evaluation of mq code. It provides methods for configuration, loading modules, and evaluating code.

§Examples

use mq_lang::DefaultEngine;

let mut engine = DefaultEngine::default();
engine.load_builtin_module();

let input = mq_lang::parse_text_input("hello").unwrap();
let result = engine.eval("add(\" world\")", input.into_iter());
assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());

Implementations§

Source§

impl<T: ModuleResolver> Engine<T, SandboxedIo<NativeIo>>

Source

pub fn new(module_resolver: T) -> Self

Creates an engine with the given module resolver and a sandboxed native Io that denies all access by default.

Source§

impl<IO: Io> Engine<DefaultModuleResolver, IO>

Source

pub fn with_default_io(io: Shared<IO>) -> Self

Creates an engine with the default module resolver and a shared Io.

The same io handles builtins and local include/import statements, so filesystem access follows one permission policy. Standard modules remain available. Use Engine::with_io when supplying a custom module resolver.

§Examples
use mq_lang::{Engine, NativeIo, SandboxedIo, Shared};

let io = Shared::new(SandboxedIo::new(NativeIo::default()));
let mut engine = Engine::with_default_io(io);
engine.load_builtin_module();
Source§

impl<T: ModuleResolver, Inner: Io> Engine<T, SandboxedIo<Inner>>

Source

pub fn is_env_allowed(&self) -> bool

Whether any environment-variable access is granted (fully or restricted to an allowlist).

Source§

impl<T: ModuleResolver, IO: Io> Engine<T, IO>

Source

pub fn with_io(module_resolver: T, io: Shared<IO>) -> Self

Like the SandboxedIo<NativeIo>-pinned Engine::new, but generic over IO and takes the Io value up front, for hosts that need to select the Io type at construction time, not just its value via set_io. Useful for e.g. a test runner that wants an in-memory mock Io installed from the start.

This only wires the evaluator side (builtins); pass the same io to DefaultModuleResolver::with_io when constructing the resolver so local-filesystem module resolution is gated consistently.

Source

pub fn set_max_call_stack_depth(&mut self, max_call_stack_depth: u32)

Set the maximum call stack depth for function calls.

This prevents infinite recursion by limiting how deep function calls can be nested. Useful for controlling resource usage. The default is 100,000 in release builds (256 in debug builds).

Source

pub fn set_timeout(&mut self, timeout: impl Into<Option<Duration>>)

Set the maximum wall-clock duration allowed for a single eval call.

Disabled by default (no timeout); pass None to disable it again. When exceeded, evaluation stops with RuntimeError::Timeout; the deadline is checked periodically inside loops and function calls, so it may be exceeded slightly before evaluation actually stops.

Source

pub fn set_capture_stack_trace(&mut self, enabled: bool)

Enables traces for uncaught VM errors.

Source

pub fn set_io(&mut self, io: Shared<IO>)

Sets the Io this engine uses for file, environment-variable, and network access: both for builtins (read_file, write_file, http, …) and for local module resolution (include/import). Defaults to an all-denied SandboxedIo wrapping NativeIo, so a host must opt in explicitly.

This only affects the evaluator side (builtins); pass the same io to DefaultModuleResolver::with_io when constructing the resolver so local-filesystem module resolution is gated consistently.

Source

pub fn set_search_paths(&mut self, paths: Vec<PathBuf>)

Set search paths for module loading.

These paths will be searched when loading external modules via the include statement in mq code.

Source

pub fn define_string_value(&self, name: &str, value: &str)

Define a string variable that can be used in mq code.

This allows you to inject values from the host environment into the mq execution context.

Source

pub fn define_string_values(&self, values: &[(&str, &str)])

Defines several string variables and publishes one VM global snapshot.

Useful when updating related values, such as the file path variables for each input.

let engine = mq_lang::DefaultEngine::default();
engine.define_string_values(&[("__FILE__", "input.md"), ("__FILE_NAME__", "input.md")]);
Source

pub fn define_value( &self, name: &str, value: RuntimeValue, ) -> Result<(), DefineValueError>

Defines an arbitrary runtime value in the current environment.

Values that retain VM execution state, such as coroutines and closures, cannot be injected. They may contain bytecode and source locations owned by another evaluation.

Source

pub fn register_fn<F, Marker>(&self, name: impl Into<Ident>, f: F)
where F: IntoHostFunction<Marker>,

Registers a native Rust function under name, callable from mq code as name(...).

Accepts two forms:

  • A raw form taking the already-evaluated call arguments as a slice and returning a single RuntimeValue: |args: &[RuntimeValue]| -> HostFnResult { .. }.
  • A typed form taking up to eight plain Rust arguments (any combination of i64, f64, String, bool, RuntimeValue, Vec<T>, or Option<T> for a ValueAdapter T), returning Result<R, HostFunctionError> for an R: ValueAdapter. Argument and return values are converted to/from RuntimeValue automatically; a wrong argument count or type is reported as a HostFunctionError rather than panicking.

Errors and panics raised by the function are caught at the call boundary and surfaced as a normal mq runtime error rather than aborting evaluation or unwinding through the evaluator; recursion depth and the configured timeout (Self::set_timeout) are enforced around each call exactly as for a user-defined function call.

A registered function only fills in a name that would otherwise be undefined: a def of the same name always takes precedence, and so does any built-in function name, whether or not Self::load_builtin_module was called: name resolution itself falls back to the built-in table before host functions are ever consulted. Host functions therefore extend the set of callable names rather than override existing ones; pick a name that doesn’t collide with a builtin.

§Examples
use mq_lang::{DefaultEngine, HostFunctionError, RuntimeValue, Shared};

let mut engine = DefaultEngine::default();
engine.load_builtin_module();

// Raw form: works with any number of arguments, matched by hand.
engine.register_fn("shout", |args: &[RuntimeValue]| match args {
    [RuntimeValue::String(s)] => Ok(RuntimeValue::String(Shared::new(format!("{}!", s.to_uppercase())))),
    _ => Err(HostFunctionError::new("shout() expects one string argument")),
});

// Typed form: argument and return conversions are handled for you.
engine.register_fn("double", |n: i64| Ok(n * 2));

let input = mq_lang::parse_text_input("hello").unwrap();
let result = engine.eval(r#"shout("hi") + to_string(double(21))"#, input.into_iter());
assert_eq!(result.unwrap(), vec!["HI!42".to_string().into()].into());
Source

pub fn load_builtin_module(&mut self)

Load the built-in function modules.

This must be called to enable access to standard functions like add, sub, map, filter, etc.

Source

pub fn import_module(&mut self, module_name: &str) -> Result<(), Box<Error>>

Import an external module by name.

The module will be searched for in the configured search paths and made available for use in mq code.

Source

pub fn load_module(&mut self, module_name: &str) -> Result<(), Box<Error>>

Load an external module by name.

The module will be searched for in the configured search paths and made available for use in mq code.

Source

pub fn eval<I: Iterator<Item = RuntimeValue>>( &mut self, code: &str, input: I, ) -> MqResult

The main engine for evaluating mq code.

The Engine manages parsing and evaluation of mq. It provides methods for configuration, loading modules, and evaluating code.

§Examples
let mut engine = mq_lang::DefaultEngine::default();
engine.load_builtin_module();

let input = mq_lang::parse_text_input("hello").unwrap();
let result = engine.eval("add(\" world\")", input.into_iter());
assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());
Source

pub fn compile(&mut self, code: &str) -> Result<CompiledProgram, Box<Error>>

Compiles mq code into a CompiledProgram that can be evaluated multiple times.

Use this with eval_compiled to avoid re-parsing the same query for each input.

Source

pub fn eval_compiled<I: Iterator<Item = RuntimeValue>>( &mut self, compiled: &CompiledProgram, input: I, ) -> MqResult

Evaluates a pre-compiled program against the given input.

Use with compile to avoid re-parsing the same query for each input file, or with a CompiledProgram constructed from a deserialized JSON AST (ast-json feature).

§Examples
let mut engine = mq_lang::DefaultEngine::default();
engine.load_builtin_module();

let compiled = engine.compile("add(\" world\")").unwrap();
let input = mq_lang::parse_text_input("hello").unwrap();
let result = engine.eval_compiled(&compiled, input.into_iter());
assert_eq!(result.unwrap(), vec!["hello world".to_string().into()].into());
Source

pub fn get_module_path(&self, module_name: &str) -> Result<String, Box<Error>>

Resolves module_name to the path its resolver loaded it from.

Source

pub const fn version() -> &'static str

The mq-lang crate version.

Trait Implementations§

Source§

impl<T: Clone + ModuleResolver, IO: Clone + Io> Clone for Engine<T, IO>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + ModuleResolver, IO: Debug + Io> Debug for Engine<T, IO>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: ModuleResolver> Default for Engine<T, SandboxedIo<NativeIo>>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<T = DefaultModuleResolver, IO = SandboxedIo> !RefUnwindSafe for Engine<T, IO>

§

impl<T = DefaultModuleResolver, IO = SandboxedIo> !Send for Engine<T, IO>

§

impl<T = DefaultModuleResolver, IO = SandboxedIo> !Sync for Engine<T, IO>

§

impl<T = DefaultModuleResolver, IO = SandboxedIo> !UnwindSafe for Engine<T, IO>

§

impl<T, IO> Forget for Engine<T, IO>

§

impl<T, IO> Freeze for Engine<T, IO>
where VmState<T, IO>: Freeze,

§

impl<T, IO> Move for Engine<T, IO>

§

impl<T, IO> Unpin for Engine<T, IO>
where VmState<T, IO>: Unpin,

§

impl<T, IO> UnsafeUnpin for Engine<T, IO>
where VmState<T, IO>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.