Skip to main content

Crate mq_lang

Crate mq_lang 

Source
Expand description

mq-lang provides a parser and evaluator for mq.

§Examples

use mq_lang::DefaultEngine;

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

let input = mq_lang::parse_markdown_input("Hello,").unwrap();
let output = engine.eval(r#"add("world!")"#, input.into_iter()).unwrap();
assert_eq!(output.into_markdown_nodes()[0].value(), "Hello,world!");

// Parse code into AST nodes
use mq_lang::{Arena, Shared, SharedCell};

let token_arena = Shared::new(SharedCell::new(Arena::new(16)));
let program = mq_lang::parse("1 + 2", token_arena).unwrap();
assert_eq!(program.len(), 1);

Enable the cst feature to use parse_recovery or CstParser for a complete source parse. The CST parser does not retain state between parses.

§Features

  • ast-json: Enables serialization and deserialization of the AST (Abstract Syntax Tree) to/from JSON format (ast_to_json / ast_from_json). Use Engine::compile and Engine::eval_compiled to execute programs constructed from deserialized ASTs. When this feature is enabled, serde and serde_json dependencies are included.

Re-exports§

pub use diagnostic::Diagnostic;
pub use suggest::suggest_name;
pub use suggest::suggest_selector;

Modules§

diagnostic
A source-agnostic diagnostic shape shared by the CST parser (used for editor/LSP scenarios that need error recovery) and other error producers. Keeping this separate from the AST-level Error/miette machinery lets consumers that don’t want a full miette::Diagnostic (e.g. mq-lsp) render consistent messages and hints without depending on miette’s rendering model.
suggest
“Did you mean” suggestions for unresolved builtin/selector names. Namespace-aware: builtins are only compared against builtins, selectors only against selectors.

Structs§

Arena
An arena allocator for efficiently storing and accessing elements.
ArenaId
A type-safe identifier for elements stored in an Arena.
AstNode
An AST node: an expression plus the id of the token it was parsed from.
AstParser
Parses a token stream into an AST, allocating tokens in the arena.
CompiledProgram
A compiled mq program bundled with its original source, returned by Engine::compile.
DefaultModuleResolver
The default resolver, combining standard library, local filesystem, and (optionally) HTTP sources.
DictIntoIter
Owning iterator over the entries of a DictMap.
DictIter
Borrowing iterator over the entries of a DictMap.
DictIterMut
Borrowing iterator over the entries of a DictMap, with mutable values.
DictMap
An insertion-ordered map from keys to runtime values.
Engine
The main execution engine for the mq.
Error
Represents a high-level error with diagnostic information for the user.
FromValueError
Error returned by from_value.
HostFunctionError
Error returned by a host-registered function, or produced while marshalling arguments and return values (see the ValueAdapter trait). Carries only a message, so it stays PartialEq-comparable and cheap to embed in RuntimeError.
HostFunctions
A registry of native Rust functions exposed to mq code under a given name.
Ident
An interned string identifier for efficient storage and comparison.
IdentWithToken
An identifier paired with the token it was parsed from.
LexerOptions
Options for the lexer.
Module
A loaded module and its top-level definitions.
ModuleLoader
Loads, caches and tracks the source of modules through a ModuleResolver.
NativeIo
Real filesystem/environment/network-backed Io implementation. This is what an embedding uses when it wants full host capability; wrap it in SandboxedIo to gate read/write/net permissions.
Position
A position in source code, representing a line and column.
Range
A range in source code, spanning from a start position to an end position.
RuntimeValues
A collection of runtime values.
SandboxedIo
Wraps an inner Io (typically NativeIo) with instance-owned read/write/net/run/env permission grants, enforced by every operation. All five default to fully denied (fail safe), and may additionally be restricted to an allowlist via PathAccess::AllowedPaths/NetAccess::AllowedDomains/ RunAccess::AllowedCommands/EnvAccess::AllowedNames.
Session
Evaluates queries one after another, carrying top-level let/var/def bindings and import/include directives from each query to the next.
Token
A lexed token with its source range.

Enums§

AstBinaryOp
A binary arithmetic or comparison operator (+ - * / % == != < <= > >=). Compiles directly to a VM opcode; see Expr::BinaryOp.
AstExpr
An expression in the AST.
AstLiteral
A literal value.
AstPattern
A pattern used by match, let and var.
AstUnaryOp
A prefix operator (! or -). Compiles directly to a VM opcode; see Expr::UnaryOp.
AttrKind
Represents an attribute that can be accessed from markdown nodes.
DefineValueError
An error returned when a value cannot be added to an Engine environment.
EnvAccess
Environment-variable access granted to SandboxedIo; same shape as PathAccess but keyed by variable name instead of filesystem path (e.g. mq-run’s --allow-env).
IoError
Error returned by Io operations. Internal plumbing type: call sites are expected to convert it into whatever domain error type they already use (e.g. ModuleError for module resolution, the builtin evaluator’s own error type) rather than surface it to miette directly.
ModuleError
Errors that can occur while loading or resolving mq modules.
NetAccess
Network access granted to SandboxedIo; same shape as PathAccess/EnvAccess but keyed by domain (e.g. mq-run’s --allow-net).
PathAccess
Filesystem access granted for one capability (read or write) of SandboxedIo.
RuntimeValue
A value in the mq runtime.
Selector
A selector for matching specific types of markdown nodes.
StringSegment
A piece of an interpolated string.
TokenKind
Represents the kind of a token in the mq language.

Constants§

BOOLEAN_LITERALS
Words that lex as boolean literals rather than identifiers.
BUILTIN_FUNCTION_NAMES
Names of the public native builtins enabled by the current features.
BUILTIN_MODULE_FILE
Source of the builtin module.
IMPLICIT_FN_ARG
Argument of fn: body. Not lexable, so it never clashes with a user name.
INTERNAL_FUNCTION_NAMES
Names of the internal native builtins enabled by the current features.
KEYWORDS
Reserved words of the language, which never lex as identifiers.
SELECTOR_NAMES
Every name accepted by Selector::from_selector_str.

Statics§

STANDARD_MODULES
Source of the modules bundled with mq, by name.

Traits§

DictKey
A type that can look up a DictMap entry: str, String or Ident.
HostFunction
A native Rust function callable from mq code, registered via HostFunctions::insert.
IntoHostFunction
Converts a Rust closure into a boxed HostFunction, as the target of crate::Engine::register_fn. Marker distinguishes the raw &[RuntimeValue] form from each typed arity below so a single closure can only ever match one implementation; hosts never need to name Marker or this trait themselves.
Io
Abstracts file, environment-variable, and network access for the mq engine. All methods are synchronous, matching the existing sync contract of ModuleResolver::resolve and the sync evaluator loop. Hosts whose only primitive is async (e.g. a browser fetch) are expected to pre-populate a cache asynchronously and answer these calls synchronously from that cache.
IoReader
Forward-only reader from Io::open_read. Dropping it closes the underlying resource.
ModuleResolver
Core interface for resolving mq module source code by name.
ValueAdapter
Converts a Rust type to and from RuntimeValue, powering the typed-argument overload of crate::Engine::register_fn. Implemented for the primitive types a host function typically wants to take or return; implement it for your own types to use them directly as arguments or return values too.

Functions§

builtin_takes_piped_input
Returns whether a call of the native builtin name with num_args arguments takes the piped value as one more argument, or None when name is no native builtin.
bytes_input
Returns a vector containing a single RuntimeValue::Bytes for raw binary input.
from_value
Deserializes a runtime value into T through its JSON form (see RuntimeValue::to_json_value).
is_builtin_function
Returns whether name is a function implemented natively by mq (e.g. len, upcase).
is_valid_ident
Returns whether name lexes as a single identifier, so keywords, literals and operators are rejected.
null_input
Returns a vector containing a single Value representing an empty input.
parse
Parses code into an AST program, allocating tokens in token_arena.
parse_html_input
Parses an HTML string, converting it to Markdown nodes.
parse_html_input_with_options
Parses an HTML string with the given conversion options, converting it to Markdown nodes.
parse_markdown_input
Parses a Markdown string and returns an iterator over Value nodes.
parse_markdown_input_with
Parses a Markdown string with the given options and returns an iterator over Value nodes.
parse_mdx_input
Parses an MDX string and returns an iterator over Value nodes.
parse_mdx_input_with
Parses an MDX string with the given options and returns an iterator over Value nodes.
parse_text_input
Parses a plain text string and returns an iterator over Value node.
raw_input
Parses a raw input string and returns a vector containing a single Value node.

Type Aliases§

AstParams
Function parameters.
DefaultEngine
An Engine using the default module resolver.
DefaultModuleLoader
A ModuleLoader using the default module resolver.
HostFnResult
Result type returned by a host function call.
ModuleId
Id of a module name in the module-name arena.
MqResult
The result of evaluating a query.
Program
A sequence of top-level or block-level nodes.
Shared
Type alias for reference-counted pointer, switches between Shared and Arc depending on “sync” feature.
SharedCell
Type alias for interior mutability, switches between SharedCell and RwLock depending on “sync” feature.