Korr

Extending Korr with Rust

Docs index

Korr is implemented in Rust, and every built-in function is an ordinary Rust closure. Adding your own fast, native functions takes a few lines, and you get the whole Rust ecosystem (crates for databases, regex, image processing, …) behind a simple Korr API.

How built-ins work

All globals are registered in builtins() in src/stdlib/mod.rs:

pub fn builtins() -> Vec<(&'static str, Value)> {
    vec![
        ("print", Value::native("print", |_, args| { /* ... */ Ok(Value::Null) })),
        ("math", sys::math_module()),
        // ...
    ]
}

Example: a text module

Create src/stdlib/text.rs:

//! text.slugify(s) and text.words(s, transform?)

use super::{arity, fn_arg, make_module, str_arg};
use crate::interp::{rt, R};
use crate::value::Value;

pub fn module() -> Value {
    make_module(vec![
        ("slugify", Value::native("text.slugify", |_, args| -> R<Value> {
            arity("text.slugify", &args, 1, 1)?;
            let s = str_arg("text.slugify", &args, 0)?;
            let mut out = String::new();
            for c in s.to_lowercase().chars() {
                if c.is_alphanumeric() {
                    out.push(c);
                } else if !out.ends_with('-') && !out.is_empty() {
                    out.push('-');
                }
            }
            let out = out.trim_end_matches('-').to_string();
            if out.is_empty() {
                return Err(rt("ValueError", "text.slugify() produced an empty slug"));
            }
            Ok(Value::string(out))
        })),
        ("words", Value::native("text.words", |it, args| {
            // Calling back into Korr: apply an optional Korr function to each word.
            arity("text.words", &args, 1, 2)?;
            let s = str_arg("text.words", &args, 0)?;
            let transform = if args.len() == 2 { Some(fn_arg("text.words", &args, 1)?) } else { None };
            let mut out = Vec::new();
            for w in s.split_whitespace() {
                let v = Value::str(w);
                out.push(match &transform {
                    Some(f) => it.call_simple(f, vec![v])?,
                    None => v,
                });
            }
            Ok(Value::array(out))
        })),
    ])
}

Register it in src/stdlib/mod.rs:

pub mod text;                       // next to the other `pub mod` lines

// inside builtins():
("text", text::module()),

Rebuild and use it:

cargo build --release
./target/release/korr -e 'print(text.slugify("Hello, Korr World!"))'          # hello-korr-world
./target/release/korr -e 'print(text.words("a b c", fn(w) => w.upper()))'      # ["A", "B", "C"]

The toolbox

Item Use
Value::Null, Value::Bool(b), Value::Int(n), Value::Float(f) simple values
Value::str(".."), Value::string(String) strings
Value::array(Vec<Value>) arrays
let mut m = Map::new(); m.set("k", v); Value::map(m) maps
Value::native(name, closure) a function value
make_module(vec![(name, value), ...]) a module
arity(name, &args, min, max) check the argument count
str_arg, int_arg, num_arg, fn_arg typed arguments with clear errors
opt_int(name, &args, i, default), opt_str(name, &args, i) optional arguments
rt(kind, message) / rt_hint(kind, message, hint) raise a Korr error
type_error(message) raise a TypeError
it.call_simple(&f, vec![args]) call a Korr function from Rust
v.truthy(), v.type_name(), v.to_display(), v.repr() inspect values

Errors you return become normal Korr errors: they can be caught with try/catch, show the line number of the Korr call, and print your hint.

Using crates

Korr’s built-in db, re and HTTP client modules are themselves thin wrappers around crates (see src/stdlib/db.rs, re.rs, fetch.rs) behind Cargo feature flags. Your fork can add any crate the same way; for example, splitting text into user-perceived characters:

# Cargo.toml
[dependencies]
unicode-segmentation = "1"
("graphemes", Value::native("text.graphemes", |_, args| {
    use unicode_segmentation::UnicodeSegmentation;
    arity("text.graphemes", &args, 1, 1)?;
    let s = str_arg("text.graphemes", &args, 0)?;
    Ok(Value::array(s.graphemes(true).map(Value::str).collect()))
})),

Every dependency you add becomes part of your supply chain; review it like your own code.

Native state

Closures can capture Rust state with Rc<RefCell<...>>; this is exactly how http.app() stores its routes (see make_app in src/stdlib/http.rs):

use std::cell::RefCell;
use std::rc::Rc;

fn counter_module() -> Value {
    let count = Rc::new(RefCell::new(0i64));
    let c = count.clone();
    make_module(vec![
        ("inc", Value::native("counter.inc", move |_, _| {
            *c.borrow_mut() += 1;
            Ok(Value::Int(*c.borrow()))
        })),
        ("get", Value::native("counter.get", move |_, _| Ok(Value::Int(*count.borrow())))),
    ])
}

Testing native code

Rust-inspired language features

You also get Rust’s ideas without writing Rust:

Rust Korr
struct + impl blocks same
match with ranges, \|, guards, _ same
0..10, 1..=10 ranges same
fn f(x: i64) -> String fn f(x: int) -> str
Option<T> ?T annotations + ?. / ??
checked arithmetic in debug builds always checked
immutable bindings const
cargo build --release single binary korr build single binary

Previous: Building Korr from source Docs index Next: Node.js vs PHP vs Python vs Korr