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). UseEngine::compileandEngine::eval_compiledto execute programs constructed from deserialized ASTs. When this feature is enabled,serdeandserde_jsondependencies 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 fullmiette::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.
- Compiled
Program - A compiled mq program bundled with its original source, returned by
Engine::compile. - Default
Module Resolver - The default resolver, combining standard library, local filesystem, and (optionally) HTTP sources.
- Dict
Into Iter - Owning iterator over the entries of a
DictMap. - Dict
Iter - Borrowing iterator over the entries of a
DictMap. - Dict
Iter Mut - 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.
- From
Value Error - Error returned by
from_value. - Host
Function Error - Error returned by a host-registered function, or produced while marshalling arguments and
return values (see the
ValueAdaptertrait). Carries only a message, so it staysPartialEq-comparable and cheap to embed inRuntimeError. - Host
Functions - A registry of native Rust functions exposed to mq code under a given name.
- Ident
- An interned string identifier for efficient storage and comparison.
- Ident
With Token - An identifier paired with the token it was parsed from.
- Lexer
Options - Options for the lexer.
- Module
- A loaded module and its top-level definitions.
- Module
Loader - Loads, caches and tracks the source of modules through a
ModuleResolver. - Native
Io - Real filesystem/environment/network-backed
Ioimplementation. This is what an embedding uses when it wants full host capability; wrap it inSandboxedIoto 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.
- Runtime
Values - A collection of runtime values.
- Sandboxed
Io - Wraps an inner
Io(typicallyNativeIo) 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 viaPathAccess::AllowedPaths/NetAccess::AllowedDomains/RunAccess::AllowedCommands/EnvAccess::AllowedNames. - Session
- Evaluates queries one after another, carrying top-level
let/var/defbindings andimport/includedirectives from each query to the next. - Token
- A lexed token with its source range.
Enums§
- AstBinary
Op - A binary arithmetic or comparison operator (
+ - * / % == != < <= > >=). Compiles directly to a VM opcode; seeExpr::BinaryOp. - AstExpr
- An expression in the AST.
- AstLiteral
- A literal value.
- AstPattern
- A pattern used by
match,letandvar. - AstUnary
Op - A prefix operator (
!or-). Compiles directly to a VM opcode; seeExpr::UnaryOp. - Attr
Kind - Represents an attribute that can be accessed from markdown nodes.
- Define
Value Error - An error returned when a value cannot be added to an
Engineenvironment. - EnvAccess
- Environment-variable access granted to
SandboxedIo; same shape asPathAccessbut keyed by variable name instead of filesystem path (e.g.mq-run’s--allow-env). - IoError
- Error returned by
Iooperations. Internal plumbing type: call sites are expected to convert it into whatever domain error type they already use (e.g.ModuleErrorfor module resolution, the builtin evaluator’s own error type) rather than surface it tomiettedirectly. - Module
Error - Errors that can occur while loading or resolving mq modules.
- NetAccess
- Network access granted to
SandboxedIo; same shape asPathAccess/EnvAccessbut keyed by domain (e.g.mq-run’s--allow-net). - Path
Access - Filesystem access granted for one capability (read or write) of
SandboxedIo. - Runtime
Value - A value in the mq runtime.
- Selector
- A selector for matching specific types of markdown nodes.
- String
Segment - A piece of an interpolated string.
- Token
Kind - 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
DictMapentry:str,StringorIdent. - Host
Function - A native Rust function callable from mq code, registered via
HostFunctions::insert. - Into
Host Function - Converts a Rust closure into a boxed
HostFunction, as the target ofcrate::Engine::register_fn.Markerdistinguishes the raw&[RuntimeValue]form from each typed arity below so a single closure can only ever match one implementation; hosts never need to nameMarkeror 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::resolveand the sync evaluator loop. Hosts whose only primitive is async (e.g. a browserfetch) 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. - Module
Resolver - Core interface for resolving mq module source code by name.
- Value
Adapter - Converts a Rust type to and from
RuntimeValue, powering the typed-argument overload ofcrate::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
namewithnum_argsarguments takes the piped value as one more argument, orNonewhennameis no native builtin. - bytes_
input - Returns a vector containing a single
RuntimeValue::Bytesfor raw binary input. - from_
value - Deserializes a runtime value into
Tthrough its JSON form (seeRuntimeValue::to_json_value). - is_
builtin_ function - Returns whether
nameis a function implemented natively by mq (e.g.len,upcase). - is_
valid_ ident - Returns whether
namelexes as a single identifier, so keywords, literals and operators are rejected. - null_
input - Returns a vector containing a single
Valuerepresenting an empty input. - parse
- Parses
codeinto an AST program, allocating tokens intoken_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
Valuenodes. - parse_
markdown_ input_ with - Parses a Markdown string with the given options and returns an iterator over
Valuenodes. - parse_
mdx_ input - Parses an MDX string and returns an iterator over
Valuenodes. - parse_
mdx_ input_ with - Parses an MDX string with the given options and returns an iterator over
Valuenodes. - parse_
text_ input - Parses a plain text string and returns an iterator over
Valuenode. - raw_
input - Parses a raw input string and returns a vector containing a single
Valuenode.
Type Aliases§
- AstParams
- Function parameters.
- Default
Engine - An
Engineusing the default module resolver. - Default
Module Loader - A
ModuleLoaderusing the default module resolver. - Host
FnResult - Result type returned by a host function call.
- Module
Id - 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.
- Shared
Cell - Type alias for interior mutability, switches between SharedCell and RwLock depending on “sync” feature.