DadoLang, systems and scripting joined.

DadoLang is a multidialect programming language with 3 dialects:

Dado .dado

Freestanding compatible, manual memory managed systems dialect which compiles to C11.

DadoScript .dados

A high level GC'd dialect which compiles to JavaScript.

DadoGL .dadogl

a high level shader dialect which compiles to SPIR-V and translates to your backend of choice.

DadoGL is spec'd, and scheduled; not implemented.
Joined

Systems and scripting, joined.

Every program using DadoScript, even those which are targeting the web, uses a harness written in Dado. On the web, this is largely performative but the little dance keeps things consistent across targets:

hello/main.dadoDado
package main

import "core:fmt"

!i32 main():
    try VM vm = #script_vm()
    defer #delete(vm)
    try Greeter g = #script_new(vm, Greeter, "World")
    defer #delete(g)
    fmt.println("Hello from Dado!")
    return i32(#script_run(g))
hello/Greeter.dadosDadoScript
class Greeter

string name = ""

void init(string who):
    name = who

void ready():
    println("Hello, ", name, ", from DadoScript!")

DadoLang uses a package system similar to Odin or Go and code from different dialects under the same package can reach each other without qualification: a script calls the package's Dado functions by their bare names, and Dado names the package's script classes by theirs and calls their methods through a handle.

score/main.dadoDado
package main

import "core:fmt"

// plain Dado, which the script calls by its bare name
i64 squared(i64 n):
    return n * n

!i32 main():
    try VM vm = #script_vm()
    defer #delete(vm)
    try Scorer s = #script_new(vm, Scorer)    // the script's class, by its bare name
    defer #delete(s)
    fmt.println("bonus from Dado: ", s.bonus(2))
    return i32(#script_run(s))
score/Scorer.dadosDadoScript
class Scorer

int bonus(int streak):
    return streak * 10

int ready():
    int total = squared(4) + bonus(3)    // Dado's squared, no import, no prefix
    println("score from DadoScript: ", total)
    return 0
Built with Dado

Real software, running today.

Dado already ships in commercial software. Building something with it? Open an issue on GitHub and tell us about it.

by SawBox

SawBox Planner

SawBox is a kitchen and cabinet planner that runs entirely in the browser, on a phone as well as a desktop. Draw your walls, place cabinets from a catalogue, adjust them by dragging or typing exact sizes, and finish with dimensioned elevations of every wall, ready for the shop.

  • 54k-line engine in Dado
  • Shell in DadoScript
  • ~40 typed boundary calls
  • 42k lines of tests
Draw the walls, place cabinets from the catalogue, and see the room in 3D
Dimensioned elevations of every wall, ready for the shop, with dimensions you can edit in place
Draw the walls, place cabinets from the catalogue, and see the room in 3D

Under the hood it's two programs with a strict division of labour. The engine, written in Dado and compiled to WebAssembly, makes every decision: geometry, the cabinet construction kernel, snapping, collisions, gesture recognition, undo and the file format. The shell, written in DadoScript, only presents what the engine publishes. The engine never calls into JavaScript; the two talk over three narrow channels.

That boundary replaced several hundred foreign-function calls in the previous version with about forty typed ones. All the hand-written JavaScript fits in a few hundred lines.

Dado enginecompiled to WebAssembly
  • typed commands in
  • versioned view-models out, read only when their revision changes
  • a zero-copy bridge over WebAssembly memory, for meshes and documents
DadoScript shellthree.js and the page
How SawBox Planner is built

Real geometry, not boxes

Each cabinet is built panel by panel by a parametric kernel: carcass, faces, reveals, toe-kicks and interiors. The engine ships its own geometry library:

  • a bounding-volume hierarchy for picking;
  • separating-axis collision with minimum-translation push-out, so a dropped cabinet slides out flush instead of sitting inside its neighbour;
  • polygon triangulation and half-edge meshes;
  • a full port of the Clipper2 polygon-clipping library.

Walls snap at their ends and where one meets another mid-length, keep their corner joints when a length changes, and take window and door openings. Cabinets seat against walls, attach to each other's sides, align, link into groups that move together, and stretch to fill a gap.

A layered engine

The engine is about 54,000 lines in seven tiers, from the core libraries up to the app. A linter enforces the layering, and the public API can only grow: nothing is ever removed from it. The app reaches the engine through exactly one package.

Rendering

  • three.js with batched geometry, so a full kitchen draws in about a dozen draw calls;
  • Phong materials with photo textures and a three-light rig;
  • shadows fitted to the objects that cast them, recomputed only when the scene changes;
  • ambient occlusion through a post-processing chain, all of it tunable from Settings.

Drawings and collaboration

Elevations switch to an orthographic view with dimension chains packed into lanes, and you can edit those dimensions in place. Projects can be co-edited: owners, editors and view-only guests share camera poses and record changes live.

Engineered to be trusted

  • About 42,000 lines of tests in 175 files, compiled into one program and run both natively and as WebAssembly in the browser.
  • 29 automated browser checks that drive the real page with real pointer input.
  • A single gate that runs all of it in under five minutes, or it fails.

Saved files and the host interface stay byte-compatible with the previous version, so the rewrite is a drop-in replacement.

One front end

One tree, one checker.

Dado and DadoScript parse into one tree and go through one checker (DadoGL will join them). DadoScript isn't a second compiler: it's a set of dialect deltas over the rules Dado is checked by, and its classes are checked as Dado declarations. Every value that crosses the boundary is checked by one relation, so the two sides can't drift apart. That one front end is also what lets the compiler optimize the boundary away. The plan is to raise or lower code across it, or duplicate a node so it's on both sides at once, with runtime checks choosing the path. Aggressive lowering, particularly on native, is how we intend to keep a program scripting through QuickJS-ng roughly competitive with a browser's JavaScript engine when comparing whole programs.

Dado nodeDadoScript nodeon both sides
The boundary

A single type system.

Dado and DadoScript share a single type system and most of a feature set. The full shared type system crosses the boundary both ways, and the compiler does the converting. You can construct and use a Dado type in DadoScript and a DadoScript type in Dado. The optimizers are built to reduce crossings anywhere possible so long as behavior is unchanged and cost analysis supports it, and interning constants shared across the boundary is on the roadmap.

Crosses both ways

  • scalars
  • strings
  • arrays
  • fixed arrays
  • tuples
  • maps
  • functions
  • class instances, as handles
  • type declarations, with slot names

Not really an FFI.

Dado has a C FFI, which isn't really an FFI but more like forward declarations to be wired up and validated at compile time. DadoScript has the same system for JavaScript modules (YMMV on validation), so JavaScript interop is as first class as C interop, on native too: C, C libraries and JavaScript all fit into one Dado project.

Targets

All you have to worry about is writing code.

Thanks to a pinned zig, DadoLang cross-compiles out of the box. Linux, MacOS and Windows are supported, and so are freestanding targets, RISC-V included. It also targets the web. On native, DadoScript runs on QuickJS-ng, embedded in your program; on the web, it runs in your browser. In either case, the glue between Dado and DadoScript is the compiler's concern. All you have to worry about is writing code.

  • Linuxx86_64 and ARM64Fully supported
  • MacOSx86_64 and ARM64Fully supported
  • WebWebAssembly, DadoScript in your browserSupported
  • Freestandingno OS, no libc, RISC-V includedSupported
  • Windowscross-compiledSupported
Toolchain

A compiler written in Dado.

dadoc is self-hosted. Its front end (syntax, types, checking, analysis, lowering, formatting and the index) is a standard collection, language:, written in Dado, and dadoc, the language server and dado fmt are programs over it. It replaces a Rust implementation of 161.6k lines with one budgeted at about 65k, because features share their logic instead of repeating it. It's also faster:

  • Lexerlines per second≈7.3M
  • Parserlines per second≈2.3M
  • Checkeragainst the Rust dadoc, per process≈6× faster

Builds and tests.

dado, the build engine, is written in Dado too. Dev builds compile with a vendored tcc where they can, one C unit per source file, so an edit recompiles only its own file. Release and cross builds use gcc, clang or the pinned zig. dado test runs every package's tests from one queue: each package is partially linked, the packages of a directory share one runner, and the runner forks a child per test, so a crash takes down one test, not the run.

Roadmap

  • DadoVM: lowering hot DadoScript to C at run time
  • raising Dado into script where the boundary costs more
  • DadoGL
Dado · .dado

Memory operations, explicit and visible.

Dado is a transpiled to C systems programming language. It has manual memory management through allocators similar to Odin or Zig (more on that later). Dado was designed to make memory operations explicit and visible. All compiler verbs including memory ones are sigiled with '#': ref []i32 list = #make([]i32, count). Dado also introduces the 'ref' type, which looks a bit like an ownership system but is not. A ref (ref T for one value from #new, ref []T for a run from #make) is a type which has the capability to delete or resize the backing memory. It can mint slices or pointers to itself normally: []i32 list_view = list[:]. Slices and pointers are regular, but they cannot be free'd or resized. Memory actions which could result in a pointer being moved are reserved explicitly for ref types. As I said before, ref types are not ownership in the Rust sense; refs can be copied and passed around freely and they DO NOT track lifetimes. #delete sets the ref it frees to nil, and the compiler refuses reading a slice or pointer after its ref may have moved or been freed, but a copy of a ref can still double free or use after free. They make memory ownership and memory viewership explicit and make slices/pointers safer to share across API boundaries.

Sigil'd allocators.

Allocating memory takes an allocator. Any memory verb which allocates can take an allocator as the trailing parameter. The sigil'd allocators are #default, #return, #stack and #heap. None of them can be reassigned; the only way to change #default is 'using', for a whole scope or a single call: factory() using #heap. '#return' is what your caller sees as #default, '#stack' allocates directly on the stack frame and is the only one that works freestanding with no setup, and '#heap' is a thin layer over C malloc and free (over linear memory on the web). The arena, bump and slab allocators in core:mem work freestanding too. Allocator is a trait, and types which implement it can be passed in 'using' and in the memory verbs.

#default

the only way to change #default is 'using', for a whole scope or a single call

#return

what your caller sees as #default

#stack

allocates directly on the stack frame and is the only one that works freestanding with no setup

#heap

a thin layer over C malloc and free (over linear memory on the web)

The allocator doesn't stop at the boundary.

An allocator set with 'using' around a call into a script (more on running scripts in Joined) is invisible to DadoScript. A script has no memory to manage, and its own objects live on its VM's heap. But the allocator doesn't stop at the boundary: when the script calls back into Dado, that Dado code sees it as #default. Wrap #script_run in an arena and every Dado allocation the script triggers lands in that arena. The allocator is picked up at the moment of the call, never captured, so a closure the script stores and calls later sees whatever allocator wraps that later call. And nothing a Dado allocator made is ever held by the script: values that cross are copied into the VM's heap, so ending the arena never leaves the script holding freed memory.

report/main.dadoDado
package main

import "core:fmt"
import "core:mem/arena"

// Called from the script. It allocates on #default, whatever that is when the script calls.
ref []char8 tag(string8 name):
    return #format("<", name, ">")

!i32 main():
    try VM vm = #script_vm()
    defer #delete(vm)
    try Report r = #script_new(vm, Report)
    defer #delete(r)

    arena.Arena frame = arena.over(#heap)
    defer arena.destroy(&frame)
    i64 status = #script_run(r) using arena.allocator(&frame)
    fmt.println("arena used: ", arena.used(frame), ", status: ", status)
    return 0
report/Report.dadosDadoScript
class Report

int ready():
    []string names = ["ada", "grace"]    // the script's own memory, on its VM's heap
    for n in names:
        println(tag(n))                   // tag's string is made in the arena
    return 0
DadoScript · .dados

High level ergonomics.

DadoScript is a strongly typed, class-based scripting language, similar to GDScript, which gives high level ergonomics to DadoLang. It compiles to JavaScript: on native it runs as ES modules on QuickJS-ng, embedded in your program, and on the web it runs in your browser. Scripts import other scripts and plain JavaScript modules, and reload while the program runs. It shares Dado's type system, but has no memory verbs or ref types. Where Dado gives you control, DadoScript keeps things simple: one int, one float, strings that just work, and no memory to manage. DadoScript remains as concerned with type safety as Dado is, so conversions are still written (int(x), string(n)), but there are far fewer types to convert between and that allows it to be very simple and flexible. Where Dado has explicit width numerics like i32, u8, f64; DadoScript has int and float. Dado reads DadoScript int and float as i64 and f64. DadoScript reads any Dado numeric as simply int or float.

Dado reads DadoScript

int→i64
float→f64

DadoScript reads Dado

i8 … u64→int
f32, f64→float

Signals.

A script class declares signals beside its fields and methods: signal hurt(int hp). Connect, disconnect and emit are spelled the same from either dialect. A script connects a method or a lambda; Dado connects a function, or a method bound to a pointer, through the handle. An emit is plain and synchronous: every connection is called, right then, in connect order, and connecting one that's already there does nothing. Each receiver's parameters cross the boundary as any call's do, so a script's int arrives in Dado as an i64.

goblin/main.dadoDado
package main

import "core:fmt"

type Score:
    i64 total

    void add(^self, i64 hp):
        self.total += hp

void log_hit(i64 hp):
    fmt.println("hit for ", hp)

!i32 main():
    try VM vm = #script_vm()
    defer #delete(vm)
    try Goblin g = #script_new(vm, Goblin)
    defer #delete(g)
    Score s = Score()
    g.hurt.connect(log_hit)          // a Dado function
    g.hurt.connect(Score.add, &s)    // a method bound to a pointer
    g.hit(4)
    g.hit(9)
    g.hurt.disconnect(Score.add, &s)
    fmt.println("total ", s.total)
    return 0
goblin/Goblin.dadosDadoScript
class Goblin

signal hurt(int hp)
signal died()

int hp = 10

void init():
    died.connect(void(): println("the goblin is gone"))

void hit(int n):
    hurt.emit(n)
    hp -= n
    if hp <= 0:
        died.emit()
Sigils

Memory and intrinsics should be loud.

One comment that is frequently made is about the heavy use of sigils in "normal" code. Dado's design philosophy is that memory and intrinsics should be loud. Every # marks something the compiler owns, and memory is the part of that you want to stand out. We don't consider memory management "normal" code, it's the single biggest source of security vulnerabilities in systems code (Microsoft and Chromium both put memory safety at around 70% of theirs). It's where your attention should go while scanning, and "quiet" code in Dado is generally safe code: subscripts are bounds checked by default, and slices and pointers can't free or move the memory they look at. The honest exceptions are FFI calls and pointers cast from rawptr, which are quiet and still yours to get right.

DadoDado
type Point: (f32 x, f32 y)

// quiet: nothing here can allocate, free or move memory
f32 dot(Point a, Point b):
    return a.x * b.x + a.y * b.y

// loud: every line that touches the heap says so
ref []Point scaled([]Point pts, f32 k):
    ref []Point out = #make([]Point, 0, #return)
    for p in pts:
        out = #append(out, (p.x * k, p.y * k))
    return out

i32 main():
    [2]Point path = [(1.0, 2.0), (3.0, 4.0)]
    ref []Point big = scaled(path[:], 2.0) using #heap
    defer #delete(big)
    fmt.println(dot(big[0], big[1]))
    return 0

Math is an intrinsic too.

The math functions are intrinsics with C's short names: #sin, #atan2, #pow, #sqrt, #floor, #fma and the rest of the set. Each is generic over f32 and f64, #abs, #min and #max take integers too, and constant arguments fold at compile time. In DadoScript they're plain globals, sin() and pow(), and a declaration of your own shadows them. And any declared type has a zero: T() is the value T t gets with no initializer.

ships/main.dadoDado
package main

import "core:fmt"

type Ship: (f32 x, f32 y, f32 heading, i32 hp)

i32 main():
    Ship s = Ship()                  // every slot zero, as `Ship s` gives
    s.hp = #max(s.hp, 3)             // integers too
    f32 dx = #cos(s.heading)         // f32 in, f32 out
    f64 r = #sqrt(2.0)               // f64 in, f64 out
    const f64 KB = #pow(2.0, 10.0)   // constant arguments fold
    fmt.println(s.hp, " ", dx, " ", r, " ", KB)
    return 0
Errors and exceptions

A failure can't be ignored by accident.

DadoLang uses a similar system to Zig when it comes to failure propagation and handling. The main difference is that failures are not types or values in DadoLang, they can only decorate a return type. A failure is never stored or passed around; it exists only at the try that handles it. In Dado, failable functions are marked explicitly with ! and can fail <code>. Calling one without try doesn't compile, so a failure can't be ignored by accident: you either handle it where it happens or pass it on, which only a failable function can do. Enums can be used to describe the failure (Why!i32), and then a switch over the code at the call site is exhaustive: name every member and no else is needed, and adding a member later breaks every switch that doesn't handle it. Normal enums never get that, since an enum value isn't guaranteed to be a member.

measure/main.dadoDado
package main

import "core:fmt"

distinct enum i32 Why: (EMPTY = 1, TOO_LONG)

Why!i32 measure(string8 name):
    if #len(name) == 0:
        fail Why.EMPTY
    if #len(name) > 8:
        fail Why.TOO_LONG
    return i32(#len(name))

// every member is named, so no `else` is needed, and adding a member breaks this switch
i32 size(string8 name):
    try i32 n = measure(name) else why:
        switch why:
            case Why.EMPTY:
                return 0
            case Why.TOO_LONG:
                return -1
    return n

i32 main():
    fmt.println(size("ada"), " ", size(""), " ", size("bartholomew"))
    return 0

In DadoScript, it's what JavaScript expects.

In DadoScript, any function can fail and failures which aren't handled simply propagate all the way out to Dado if not caught somewhere. This behavior is what's expected of JavaScript code. A failure is an Error with a message, a code, a location and a trace, and faults like an index out of bounds or a missing key are ordinary failures a try can catch. When a failure reaches Dado, a try gets the script's own code and #script_error() gets its text. Without a try, the VM decides: by default the program ends, or a VM made with script.CONTINUE hands back a zero value and keeps going, the way a game keeps running past a broken mod. It works the other way too: a Dado failure inside a function a script called is thrown into the script as an Error.

ages/main.dadoDado
package main

import "core:fmt"

!i32 main():
    try VM vm = #script_vm()
    defer #delete(vm)
    try Ages ages = #script_new(vm, Ages)
    defer #delete(ages)
    [3]i64 xs = [31, -4, 52]
    fmt.println("oldest: ", ages.oldest(xs))
    try i64 n = ages.check(-1) else code:
        fmt.println("failed with ", code, ": ", #script_error())
        return 0
    fmt.println(n)
    return 0
ages/Ages.dadosDadoScript
class Ages

int check(int age):
    if age < 0:
        fail Error("age can't be negative", 16)
    return age

int oldest([]int ages):
    int best = 0
    for a in ages:
        try int ok = check(a) else e:
            println("skipping: ", e)
            continue
        if ok > best:
            best = ok
    return best
Types

Every type is a tuple.

  • f32 n = 5.0
  • [1]f32 n = [5.0]
  • (f32) n = (5.0)

DadoLang is built on a type system where every type is a tuple. Even something like f32 n = 5.0 is equivalent to [1]f32 n = [5.0] or (f32) n = (5.0). An array is a tuple whose slots share a type, and that uniform stride is what lets it be indexed at runtime and gives it array-like behaviors (a mixed tuple can only be indexed by a constant). Types are structural and type Point: [2]f32 is equivalent to type Vec2: [2]f32 or even type Vec2: (f32 x, f32 y). Names are what's called a view, and they can be exchanged, stripped or created at anytime. A type is a model of memory, while a view is a model of how we interpret that memory. Identity is opt-in: nominal typing is possible through the distinct keyword, distinct type ResourceID: u8, which adds a real tag the compiler checks and then erases in the emitted C. Methods are also a part of the view and not the data, so having a method in a type does not prevent it from being passed as another type without a cast. Trait conformance is different, it's declared, so a structural twin of a Drawable type isn't a Drawable until it says so.

In practice, the tuple model shows up as things that just work: (3, 4) is already a Point, functions return multiple values as a tuple, q.xy and colour.rgb swizzle any vector, and #slots(p) spreads a value into an argument list. Under the hood, your types and monomorphisations collapse in the emitted product to a narrow subset of what you actually wrote, which helps keep boundaries thinner and binaries compact. Four names for one shape, and one generic called with all of them:

DadoDado
type Point: (f32 x, f32 y)
type Vec2: (f32 u, f32 v)
type Size: [2]f32

T first([2]$T pair):
    return pair[0]

f32 sum(Point p):
    return p.x + p.y

i32 main():
    Point a = (1.0, 2.0)
    Vec2 b = (3.0, 4.0)
    Size c = [5.0, 6.0]
    [2]f32 d = [7.0, 8.0]
    f32 t = first(a) + first(b) + first(c) + first(d) + sum(b) + sum(c)
    return i32(t)

The emitted C has one struct for all four types and one copy of first, and sum takes a Vec2 and a Size with no conversion:

emitted Cemitted C
typedef struct dado_tup2_f32_f32 dado_tup2_f32_f32;
float dado_main_sum(dado_tup2_f32_f32 dado_l_p);
float dado_main_0__first__dado____f32(dado_tup2_f32_f32 dado_l_pair);
Traits

Methods, never fields.

Traits in DadoLang prescribe methods, never fields. A type takes a trait on with using at its head, and conformance is declared, not inferred: the compiler checks it right there at the using and tells you which method is missing. A trait can carry default bodies, and traits can extend other traits. The Allocator from the memory section is just a trait.

A trait gets used two ways, and the difference is where you write it. As a parameter's whole type it's a binder: the function is compiled once per implementer and every call inside is direct, so there's no dispatch cost at all. Anywhere else (a field, a local, an array element) it's a trait value: two words, the implementer's address and which declaration it is, dispatched at run time through a generated switch rather than a vtable. A trait value is a view. It owns nothing and follows every rule a slice does, so it can't outlive what it points at.

a parameter's whole type

A binder

Compiled once per implementer, every call inside is direct.

anywhere else

A trait value

Two words, the implementer's address and which declaration it is, dispatched at run time.

traits/main.dadoDado
package main

import "core:fmt"

trait Shape:
    f32 area(self)
    void describe(self):                  // a default, for any shape that doesn't write its own
        fmt.println("a shape of area ", self.area())

type Rect using Shape: (f32 w, f32 h)
    f32 area(self):
        return self.w * self.h

type Circle using Shape: (f32 r)
    f32 area(self):
        return 3.14159 * self.r * self.r
    void describe(self):
        fmt.println("a circle of radius ", self.r)

// a binder: compiled once per shape, every call direct
f32 doubled(Shape s):
    return s.area() * 2.0

i32 main():
    Rect r = (3.0, 4.0)
    Circle c = (1.0)
    fmt.println(doubled(r), " ", doubled(c))
    [2]Shape scene = [r, c]               // trait values: dispatched at run time
    for s in scene:
        s.describe()
    return 0

DadoScript classes take traits on with the same using, and a script's trait is a type you can hold and call through. A script can't take on a trait Dado declares yet; that part of the boundary isn't built.

Unions

Exactly one of a closed set.

A union in DadoLang is a discriminated union: exactly one of a closed set of member types, plus a tag saying which. The member's type is the discriminant, so nothing gets a label and no two members can be the same type. There's no construction syntax; putting a value in a union is a written conversion, Event(at). Getting it back out happens in exactly two places: a guarded read, e.(Click), which gives you the value and whether it was one, and a switch, where each arm binds the narrowed member. Unions are closed by construction, so a switch that names every member needs no else, same as a failure enum and unlike a normal enum.

unions/main.dadoDado
package main

import "core:fmt"

type Click: (i32 x, i32 y)
type Key: (char8 key, bool down)
type Resize: (i32 w, i32 h, bool full)
union Event: (Click, Key, Resize)

void handle(Event e):
    switch e:                              // every member named, so no `else`
        case Click c:
            fmt.println("click at ", c.x, ",", c.y)
        case Key k:
            fmt.println("key ", k.key, " down: ", k.down)
        case Resize r:
            fmt.println("resize to ", r.w, "x", r.h)

i32 main():
    Click at = (10, 20)
    Event e = Event(at)                    // widening is a written conversion
    handle(e)
    (Click c, bool ok) = e.(Click)         // the guarded read: the value and whether it was one
    fmt.println(ok, " ", c.x)
    (Key _, bool is_key) = e.(Key)
    fmt.println(is_key)
    return 0

For C interop there's cunion, C's own untagged union. Since nothing records which member was written last, the compiler refuses anything that would need the tag: no switch, no guarded read, no printing. Both kinds can be exported to C.

Unions are Dado only for now. They're planned for DadoScript but not built yet.