Skip to main content

Crate nybl

Crate nybl 

Source
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

  • run parses and executes one isolated program with the tree-walker.
  • NyblInstance loads a program once and lets a host repeatedly call root-level pub fn entry points while program state remains live.
  • ReplSession retains declarations across source submissions and is intended for interactive tools.
  • parse, parse_with_warnings, and parse_with_warnings_and_resolver expose 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)    // 1

A 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 NyblHost building blocks for embedders.
lexer
math
Tiny f64 math facade that works on both the default (std) build and the no_std opt-in. core::f64 doesn’t expose sqrt / sin / cos / etc. — those methods live in std::f64’s platform-dependent math library — so the no_std build has to forward to the pure-Rust libm crate instead. The std build stays dep-free and calls the native f64 methods 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 behind nybl-std (on by default).
suggest
“Did you mean?” suggestions — used by error paths to turn Variable lenght not found into a hint that points at length (or len) when those exist in the surrounding scope.
value
Value type for the Nybl interpreter.
value_conversion
Rust ↔ Value conversions for embedders.

Macros§

nybl_value
Construct a tracked, depth-checked Nybl value with JSON-like syntax.

Structs§

EntryPoint
A public root function exposed by a loaded crate::NyblInstance.
NyblInstance
A loaded tree-walker program whose globals, imports, functions, types, methods, RNG state, and returned callbacks remain live across calls.
NyblLimits
Resource limits enforced during execution.
PreparedEntry
An opaque, pre-resolved public entry point for repeated host dispatch.
ReplSession
Persistent state for an interactive REPL session. Unlike the one-shot run API, a ReplSession carries its scopes, fns, user types, method tables, and import cache across calls, so session.eval("let x = 5") followed by session.eval("print(x)") sees the same x. Persistent state for an interactive REPL session. Build once with Self::new, then call Self::eval for each fresh line / block the user types. State carried across calls: every let / const / fn / struct / enum / method declaration, every use’d module’s bindings and aliases, the global rng seed, and the import cache.

Constants§

DEFAULT_MAX_NESTING
Default NyblLimits::max_nesting for both presets.

Traits§

NyblHost
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 parse in 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_warnings but follows every top-level use statement via the supplied resolver so the exhaustiveness check can see imported enums. resolver has the same shape as NyblHost::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 pattern against value. On success, appends any captured (name, Value) bindings to bindings and returns true; on failure, returns false and leaves bindings in 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. Returns None if the name isn’t in scope.
run
Run a Nybl program with the given host and limits.

Type Aliases§

TypeResolveFn
Type alias for the resolver closure pattern_matches expects. Resolver that turns a source-level type reference — optional namespace plus bare name (m.Color vs plain Color) — into the declaring module’s path. Pattern matching threads this through so a pattern like Color::Red only matches values whose module identity agrees with the current scope’s binding of Color.