nybl-lang 0.5.0

A small, embeddable, dynamically-typed programming language with zero dependencies
Documentation

nybl-lang

The core of Nybl — a small, dynamically-typed, embeddable scripting language for Rust applications.

Hand your users or your AI a real programming language at runtime, without shipping a compiler to the target machine.

Note: Nybl is experimental and not yet battle-tested. Fine for tooling, scripting, and embedding experiments; use with care in production.

What's in this crate

nybl-lang is the language core:

  • Lexer + parser producing a typed AST
  • Tree-walking interpreter (nybl::run) — simplest runtime, works everywhere
  • Persistent interpreter (nybl::NyblInstance) — load once, then call explicit pub fn entries while globals, modules, callbacks, and RNG state remain live
  • NyblHost trait — the only thing embedders need to implement to wire Nybl into their Rust app
  • Value type + builtin operators — the shared runtime surface every Nybl engine uses
  • Opaque HostValue handles — retain host resources in Nybl and dispatch methods through NyblHost::call_method without exposing their Rust payloads
  • Transactional ref parameters — explicit copy-in/copy-out updates to deep mutable caller places, with rollback on errors
  • Variadic functions and explicit module surfaces — final ..rest parameters and pub { ... } export allow-lists
  • Resource limits (NyblLimits) — step, tracked-memory, and code-nesting budgets, plus a fixed function-call depth cap; module loads share them and cost one step per token

For a faster runtime (2–3× this crate's tree-walker, same semantics), add nybl-vm. For an AOT path to native Rust, see nybl-compile.

Selling points

  • Embeddable. One trait (NyblHost) to implement; everything else is handled by the engine.
  • Zero Rust deps Nothing to audit in your supply chain.
  • no_std support via the no_std feature (uses the libm crate internally for float math, nothing else).
  • WASM-compatible. Builds clean for wasm32-unknown-unknown. Use it in browsers, edge workers, or wherever you can run Rust.
  • Sandboxed by default. NyblLimits caps step count, tracked memory, and nesting across active calls (max_nesting), and the runtime caps function-call depth, so runaway user scripts halt cleanly. Native stack use is bounded too: under default limits a thread of 10 MiB (release) or 128 MiB (debug) suffices for any program, and the requirement scales roughly with max_nesting.

Quick start

[dependencies]
nybl-lang = "0.5"
use nybl::{run, NyblError, NyblHost, NyblLimits, Value};

struct MyHost;

impl NyblHost for MyHost {
    fn call(&mut self, name: &str, _args: &[Value], _line: u32)
        -> Option<Result<Value, NyblError>>
    {
        // Return Some(Ok(...)) to handle a custom function call,
        // Some(Err(...)) to raise, None to defer to builtins.
        match name {
            "greet" => Some(Ok(Value::from("hello!"))),
            _ => None,
        }
    }

    fn on_print(&mut self, msg: &str) {
        println!("{msg}");
    }
}

fn main() {
    let mut host = MyHost;
    let limits = NyblLimits::standard();
run(r#"print(greet())"#, &mut host, &limits).unwrap();
}

The language normally passes independent values. A user-defined function can opt into a caller update with ref at both sites:

fn increment(ref value) {
  value += 1
}

let count = 0
increment(ref count)
print(count)    // 1

Reference calls stage their changes and commit only after a normal return. See the reference-parameters guide for target, rollback, forwarding, method, and host-boundary rules.

For a stateful plugin rather than a one-shot script, declare root entry points with pub fn, then load and call an instance:

use nybl::{NyblInstance, NyblLimits, Value};

let mut instance = NyblInstance::load(
    "let total = 0\npub fn add(n) { total += n; return total }",
    &mut host,
    &NyblLimits::standard(),
)?;
let value = instance.call("add", &[Value::Int(3)], &mut host)?;

entry_points() exposes each public entry's name and arity, while call_value() invokes a callback returned by that same instance. See the stateful embedding guide for lifecycle, affinity, limits, and error-state behavior.

Host arguments support borrowed or owned typed extraction through Value::to_rust (&str, integers, Vec<T>, Option<T>, Result<T, E>, and deterministic BTreeMap<String, T>). Use the fallible, JSON-like nybl_value! macro to construct nested values while retaining Nybl's depth checks.

Hosts can also return Value::new_host("type", payload) for an opaque resource handle and implement NyblHost::call_method. Handles clone cheaply, compare by identity, display as <host type>, and keep host-side mutations outside Nybl's transaction and memory-accounting semantics. See the embedding guide.

Features

feature default what it does
std yes enables Rust standard-library integration, including stderr diagnostics and the std-only legacy ambient-memory compatibility APIs. If Cargo unifies std and no_std, this feature wins.
nybl-std yes bundles the Nybl stdlib (use std.math, std.json, std.collections, std.iter, std.string, std.test) as &'static str constants reachable via [nybl::stdlib::resolve]
no_std no opt in for bare-metal / embedded / edge wasm targets. Pulls in libm for float math. Enable with default-features = false, features = ["no_std"] (add "nybl-std" too if you want the bundled stdlib on those targets).

A minimal std build — core language only, no bundled Nybl stdlib:

nybl-lang = { version = "0.5", default-features = false, features = ["std"] }

For compatibility, omitting both std and no_std also retains std behavior; genuine no_std builds must explicitly select no_std with default features disabled.

The walker and VM carry memory accounting through an explicit per-engine MemoryContext, so nested or concurrent executions cannot charge one another. This changes custom true-no_std runtime integrations: the legacy ambient nybl_memory_* functions and ActiveMemoryGuard are now std-only. Code that used those hooks must pass a MemoryContext through the context-aware internal constructors and mutation helpers instead. Values created by a host through the public Value constructors are untracked until an engine mutation adopts their backing storage into its own account.

WASM example

[dependencies]
nybl-lang = { version = "0.5", default-features = false, features = ["no_std", "nybl-std"] }

Build for wasm32-unknown-unknown as usual. See nybl-vm for the faster runtime if you need it.

Related crates

  • nybl-vm — bytecode compiler + VM, 2–3× faster than this crate's walker, same API
  • nybl-compile — AOT Nybl → Rust transpiler for native-speed scripts
  • nybl-sys — ready-made StdHost with filesystem / stdio / env / time
  • nybl-cli — the nybl command-line tool (nybl run, nybl compile, REPL)

License

Dual-licensed under MIT or Apache 2.0, at your option.