Expand description
Nybl language core and tree-walking runtime.
Nybl is a small, dynamically typed scripting language designed to be
embedded in Rust applications. The core runtime has no ambient access to
the filesystem, network, environment, clock, or standard I/O: a program
can only reach capabilities exposed through NyblHost.
§Choose an execution API
runparses and executes one isolated program with the tree-walker.NyblInstanceloads a program once and lets a host repeatedly call root-levelpub fnentry points while program state remains live.ReplSessionretains declarations across source submissions and is intended for interactive tools.parse,parse_with_warnings, andparse_with_warnings_and_resolverexpose the parser and static diagnostics without executing the program.
The nybl-vm crate provides a faster bytecode
implementation with equivalent one-shot and persistent APIs.
nybl-compile transpiles the same language
to Rust.
§One-shot embedding
use nybl::{NyblError, NyblHost, NyblLimits, Value};
struct Host {
output: Vec<String>,
}
impl NyblHost for Host {
fn call(
&mut self,
name: &str,
args: &[Value],
line: u32,
) -> Option<Result<Value, NyblError>> {
match (name, args) {
("double", [Value::Int(value)]) => {
Some(Ok(Value::Int(value * 2)))
}
("double", _) => Some(Err(NyblError::runtime(
"double(value) expects one int",
line,
))),
_ => None,
}
}
fn on_print(&mut self, message: &str) {
self.output.push(message.to_owned());
}
}
let mut host = Host { output: Vec::new() };
nybl::run(
"print(double(21))",
&mut host,
&NyblLimits::standard(),
).unwrap();
assert_eq!(host.output, ["42"]);§Reference parameters
Nybl normally passes independent values. User-defined functions may opt
into explicit, second-class reference parameters by writing ref at both
the declaration and call:
fn increment(ref value) {
value += 1
}
let count = 0
increment(ref count)
print(count) // 1A reference argument must be a distinct mutable field/index place rooted in
a let binding.
The callee receives a staged copy; every reference target commits together
only after a normal return and rolls back together on runtime or resource
errors. Reference parameters may be forwarded but not captured. Built-in
and host functions are value-only.
User-defined methods may declare ref self to update a mutable
place receiver. Method-call syntax supplies that reference
implicitly (counter.increment()); the receiver joins explicit reference
arguments in the same transaction. Ordinary self receivers are read-only,
and assigning through one is a parse error with a ref self hint.
NyblInstance::call and NyblInstance::call_value also accept values,
not Nybl bindings, and reject ref-bearing callables before execution. Keep
host-facing pub fn entries value-only and perform ref calls inside Nybl.
The complete language contract is in the reference-parameters
guide.
§Persistent programs
A persistent program explicitly publishes its host-callable ABI with
direct root-level pub fn declarations:
let mut host = Host;
let mut instance = NyblInstance::load(
"let count = 0\npub fn next() { count += 1; return count }",
&mut host,
&NyblLimits::standard(),
).unwrap();
assert_eq!(
instance.call("next", &[], &mut host).unwrap().inspect(),
"1",
);
assert_eq!(
instance.call("next", &[], &mut host).unwrap().inspect(),
"2",
);§Rust values
Value::to_rust, IntoValue, FromValue, and the
nybl_value! macro provide checked conversions at host boundaries.
Conversions include strict numeric scalars, borrowed and owned strings,
Vec<T>, Option<T>, Result<T, E>, and deterministic
BTreeMap<String, T> dictionaries. Recursive construction remains
fallible so Nybl’s maximum value-depth invariant cannot be bypassed.
§Limits and features
NyblLimits bounds executed steps and tracked allocations. All engines
also enforce a fixed function-call depth. Limit failures are fatal and
cannot be swallowed by Nybl’s try_call.
The default std feature enables Rust standard-library integration. The
separate default nybl-std feature bundles the std.math, std.iter,
std.collections, std.string, std.json, and std.test modules as Nybl
source; resolve them through stdlib::resolve. Disable default features
to omit the bundled modules while keeping Rust std by explicitly enabling
std. A genuine no_std build uses default-features = false plus the
opt-in no_std feature, which replaces standard-library floating-point
operations with libm. If Cargo unifies std and no_std, std wins.
The complete language and embedding guides live at https://nybl-lang.com/docs/.
Re-exports§
pub use error::NyblError;pub use error::NyblWarning;pub use parser::ParamMode;pub use parser::Stmt;pub use parser::count_instructions;pub use ref_params::validate_call_modes;pub use ref_params::validate_value_only_call_modes;pub use value::HostValue;pub use value::Value;pub use value_conversion::FromValue;pub use value_conversion::IntoValue;pub use value_conversion::ValueConversionError;pub use value_conversion::ValuePathSegment;pub use evaluator::pattern_matches;
Modules§
- ast_
depth - Static nesting depth of executable code.
- builtins
- Language-level builtins (
range,str,int,type,len, …) and the shared argument-validation helpers used across the runtime. - check
- Static checks that run after parsing and before execution.
- error
- Error type for the Nybl interpreter.
- error_
messages - Shared error-message format helpers.
- host
- Ready-made
NyblHostbuilding blocks for embedders. - lexer
- math
- Tiny
f64math facade that works on both the default (std) build and theno_stdopt-in.core::f64doesn’t exposesqrt/sin/cos/ etc. — those methods live instd::f64’s platform-dependent math library — so the no_std build has to forward to the pure-Rustlibmcrate instead. The std build stays dep-free and calls the nativef64methods directly. - memory
- Allocation-owned memory accounting for Nybl execution.
- methods
- naming
- Identifier classification: the shared rules every engine and the parser consult to sort a name into naming buckets.
- ops
- Operator primitives shared across execution engines.
- parser
- precheck
- Lightweight reserved-binding precheck retained for embedder compatibility.
- ref_
params - Shared
ref-parameter mode checks and diagnostics. - stdlib
- Bundled Nybl standard library (
use std.math,std.json,std.collections,std.iter,std.string,std.test). Feature-gated behindnybl-std(on by default). - suggest
- “Did you mean?” suggestions — used by error paths to turn
Variablelenghtnot foundinto a hint that points atlength(orlen) when those exist in the surrounding scope. - value
- Value type for the Nybl interpreter.
- value_
conversion - Rust ↔
Valueconversions for embedders.
Macros§
- nybl_
value - Construct a tracked, depth-checked Nybl value with JSON-like syntax.
Structs§
- Entry
Point - A public root function exposed by a loaded
crate::NyblInstance. - Nybl
Instance - A loaded tree-walker program whose globals, imports, functions, types, methods, RNG state, and returned callbacks remain live across calls.
- Nybl
Limits - Resource limits enforced during execution.
- Prepared
Entry - An opaque, pre-resolved public entry point for repeated host dispatch.
- Repl
Session - Persistent state for an interactive REPL session. Unlike the one-shot
runAPI, aReplSessioncarries its scopes, fns, user types, method tables, and import cache across calls, sosession.eval("let x = 5")followed bysession.eval("print(x)")sees the samex. Persistent state for an interactive REPL session. Build once withSelf::new, then callSelf::evalfor each fresh line / block the user types. State carried across calls: everylet/const/fn/struct/enum/ method declaration, everyuse’d module’s bindings and aliases, the global rng seed, and the import cache.
Constants§
- DEFAULT_
MAX_ NESTING - Default
NyblLimits::max_nestingfor both presets.
Traits§
- Nybl
Host - Extension point for embedders to add custom built-in functions.
Functions§
- parse
- Parse Nybl source into an AST (useful for instruction counting).
- parse_
with_ warnings - Parse Nybl source and run the static check pass, returning
both the AST and any non-fatal warnings (currently:
match-exhaustiveness). Prefer this over
parsein tools that surface diagnostics to users — the CLI uses it to print warnings before running the program. - parse_
with_ warnings_ and_ resolver - Like
parse_with_warningsbut follows every top-levelusestatement via the supplied resolver so the exhaustiveness check can see imported enums.resolverhas the same shape asNyblHost::resolve_module. - pattern_
matches - The core pattern matcher. Re-exported so engines beyond the
tree-walker (the bytecode VM, the AOT runtime) can apply the
same structural rules without re-implementing them.
The core pattern matcher. Re-exported so engines beyond the
tree-walker (the bytecode VM, the AOT runtime) can apply the
same structural rules without re-implementing them.
The core pattern matcher. Re-exported so engines beyond the
tree-walker (the bytecode VM, the AOT runtime) can apply the
same structural rules without re-implementing them.
Attempt to match
patternagainstvalue. On success, appends any captured(name, Value)bindings tobindingsand returnstrue; on failure, returnsfalseand leavesbindingsin an undefined state — it’s the caller’s responsibility to discard it. - resolve_
type_ in - Shared scope walker for resolving source-level type
references to the declaring module. Re-exported because VM
and AOT both need to build per-frame type resolvers when
calling
pattern_matches— the identity comparison lives on the matcher side, but the scope lookup is identical across engines. Walk a pair of scope stacks to resolve a source-level type reference. This is free-standing so the pattern matcher can be called with a borrow of the evaluator’s tables without needing the evaluator itself. ReturnsNoneif the name isn’t in scope. - run
- Run a Nybl program with the given host and limits.
Type Aliases§
- Type
Resolve Fn - Type alias for the resolver closure
pattern_matchesexpects. Resolver that turns a source-level type reference — optional namespace plus bare name (m.Colorvs plainColor) — into the declaring module’s path. Pattern matching threads this through so a pattern likeColor::Redonly matches values whose module identity agrees with the current scope’s binding ofColor.