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>>
impl<T: ModuleResolver> Engine<T, SandboxedIo<NativeIo>>
Source§impl<IO: Io> Engine<DefaultModuleResolver, IO>
impl<IO: Io> Engine<DefaultModuleResolver, IO>
Sourcepub fn with_default_io(io: Shared<IO>) -> Self
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>>
impl<T: ModuleResolver, Inner: Io> Engine<T, SandboxedIo<Inner>>
Sourcepub fn is_env_allowed(&self) -> bool
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>
impl<T: ModuleResolver, IO: Io> Engine<T, IO>
Sourcepub fn with_io(module_resolver: T, io: Shared<IO>) -> Self
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.
Sourcepub fn set_max_call_stack_depth(&mut self, max_call_stack_depth: u32)
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).
Sourcepub fn set_timeout(&mut self, timeout: impl Into<Option<Duration>>)
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.
Sourcepub fn set_capture_stack_trace(&mut self, enabled: bool)
pub fn set_capture_stack_trace(&mut self, enabled: bool)
Enables traces for uncaught VM errors.
Sourcepub fn set_io(&mut self, io: Shared<IO>)
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.
Sourcepub fn set_search_paths(&mut self, paths: Vec<PathBuf>)
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.
Sourcepub fn define_string_value(&self, name: &str, value: &str)
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.
Sourcepub fn define_string_values(&self, values: &[(&str, &str)])
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")]);Sourcepub fn define_value(
&self,
name: &str,
value: RuntimeValue,
) -> Result<(), DefineValueError>
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.
Sourcepub fn register_fn<F, Marker>(&self, name: impl Into<Ident>, f: F)where
F: IntoHostFunction<Marker>,
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>, orOption<T>for aValueAdapterT), returningResult<R, HostFunctionError>for anR: ValueAdapter. Argument and return values are converted to/fromRuntimeValueautomatically; a wrong argument count or type is reported as aHostFunctionErrorrather 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());Sourcepub fn load_builtin_module(&mut self)
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.
Sourcepub fn import_module(&mut self, module_name: &str) -> Result<(), Box<Error>>
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.
Sourcepub fn load_module(&mut self, module_name: &str) -> Result<(), Box<Error>>
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.
Sourcepub fn eval<I: Iterator<Item = RuntimeValue>>(
&mut self,
code: &str,
input: I,
) -> MqResult
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());Sourcepub fn compile(&mut self, code: &str) -> Result<CompiledProgram, Box<Error>>
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.
Sourcepub fn eval_compiled<I: Iterator<Item = RuntimeValue>>(
&mut self,
compiled: &CompiledProgram,
input: I,
) -> MqResult
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());Trait Implementations§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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