Thoxa

A statically typed, expression-oriented programming language. The compiler translates Thoxa to C, and a C compiler builds that into a native executable.

Pre-alphaLinux x86-64No releases yetManualSource

Design

Automatic memory, without a collector or a borrow checker. Values are reference counted. Integers, floats, and small records are stored inline; strings, arrays, and maps are counted and copied on write, so a value never changes under another binding. There are no lifetimes and no collection pauses. Files, sockets, and databases close when their last reference goes.

Errors are values.Trial<T, E> and May<T> are ordinary unions from the standard library, and ? hands a failure back to the caller. There are no exceptions. A panic (an index out of range, a division by zero) is for bugs, and it ends only the task it happens in.

The type is the schema.Int64 where >= 1 is a type, and "small" | "large" is a closed set of strings. From a type definition the compiler writes a JSON reader that reports every bad field, a form reader, and an encoder. There are no derive macros, schema objects, or runtime reflection.

Close to C. The output is C. extern fn calls a C function directly, a type with body fields has C layout, and integer behaviour is defined: arithmetic wraps, narrowing is checked, and division by zero panics instead of being undefined.

What a small web service needs is in the language. Tag literals build HTML as values, a type body of GET "/path" clauses is a router, sql"…" quotes every value it interpolates, and --> starts a task whose socket operations park instead of blocking: one OS thread, no async, no await. The standard library has an HTTP/1.1 server and SQLite. This site is a Thoxa program, and its manual page is rendered from Markdown by Thoxa code.

Features

Types
Int64, Int32, UInt32, UInt64, Byte, Float64, Bool, String, Bytes; products and unions; literal types; refinements (where); generic types; function types.
Traits
trait and conform: a type conforms only by declaring it, and a trait writes the members its conforming types share. Getters and setters read like fields; self is the receiver.
Inference
Local inference for let. Return types are inferred for functions and methods without an annotation.
Matching
Constructor, literal, and or-patterns, with guards. A match on a union must cover every member.
Functions
Positional or named arguments, defaults, and multi-clause functions that dispatch on parameter types, literal types included.
Values
Declared Equatable, Hashable, and Ordered, field by field or written by hand: ==, map keys, and < on your own types. Array and Map copy on write; a Map keeps insertion order.
Errors
May, Trial, and ?. A panic ends the task it happens in, not the process.
Memory
Reference counting. A type that conforms to Resource owns something outside the program and releases it with its last reference.
Concurrency
--> starts a task. Socket operations park it until they can proceed. One OS thread.
Data
T.read for JSON text and T.readForm for forms; encode for output; Json literals; typed route body parameters.
Conversions
x as T converts, and its type says whether it can fail; x as? T converts or returns the failure. A type adds conversions into itself with from clauses.
Web
Tag literals (Node), route clauses, an HTTP/1.1 server with static files and server-sent events, and sql"…" with SQLite.
C
extern fn, C-layout types, Address<T>, and fixed-size arrays.
Tools
thoxa run, build, check (with --json), and lsp; a Zed extension.

The manual has the rules for each.

Samples

Each sample is a complete program from workloads/landing/samples. cargo make test runs each one and compares its output with what is shown here; the server, which never exits, is compiled but not run.

Types and match§

A product type lists its fields; a union lists its members. match takes a union apart, with guards, and says so at compile time when a member is missing. A type that declares Equatable compares field by field.

import logging, { info } from "std/logging"

type Circle(radius: Float64)
type Rect(width: Float64, height: Float64)
conform Rect to Equatable
type Triangle(base: Float64, height: Float64)
type Shape = Circle | Rect | Triangle

fn area(shape!: Shape) -> Float64 {
    match shape {
        Circle(radius) => 3.14159 * radius * radius
        Rect(width, height) => width * height
        Triangle(base, height) => base * height / 2.0
    }
}

fn describe(shape!: Shape) -> String {
    match shape {
        Rect(width, height) if width == height => "a square"
        Rect => "a rectangle"
        Circle => "a circle"
        Triangle => "a triangle"
    }
}

fn main() {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    let shapes: Array<Shape> = [
        Circle(radius: 1.0),
        Rect(width: 2.0, height: 2.0),
        Triangle(base: 3.0, height: 4.0),
    ]
    for shape in shapes {
        info("{describe(shape)}: {area(shape)}")
    }
    info("{Rect(width: 2.0, height: 2.0) == Rect(width: 2.0, height: 2.0)}")
    0
}

Output

a circle: 3.14159
a square: 4.0
a triangle: 6.0
true

Errors are values§

Trial<T, E> (Pass / Fail) and May<T> (Has / Not) are ordinary unions from std/fallible. ? unwraps a Pass or returns the Fail to the caller. There are no exceptions.

import { Has, Not, May, Pass, Fail, Trial } from "std/fallible"
import { parseUInt } from "std/string"
import logging, { info } from "std/logging"

type Setting(name: String, value: Int64)

fn parseLine(line!: String) -> Trial<Setting, String> {
    let parts = match line.splitOnce("=") {
        Has(found) => found
        Not => return Fail("no `=` in `{line}`")
    }
    let value = match parseUInt(parts.after.trim()) {
        Has(number) => number
        Not => return Fail("`{parts.after.trim()}` is not a number")
    }
    Pass(Setting(name: parts.before.trim(), value))
}

fn parseAll(lines!: Array<String>) -> Trial<Array<Setting>, String> {
    mut settings: Array<Setting> = []
    for line in lines {
        settings.append(parseLine(line)?)
    }
    Pass(settings)
}

fn main() -> Int64 {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    let files = [
        ["port = 8080", "workers = 4"],
        ["port = 8080", "workers four"],
        ["port = eighty"],
    ]
    for lines in files {
        match parseAll(lines) {
            Pass(found) => info("{found.count} settings, port {found[0].value}")
            Fail(reason) => info("error: {reason}")
        }
    }
    0
}

Output

2 settings, port 8080
error: no `=` in `workers four`
error: `eighty` is not a number

Types that check their values§

where narrows a type; a literal union names the values a string may take. json as T (or T.read for text) builds a T and reports every problem it finds; encode writes any value back out. Nothing is derived or registered: the compiler reads the type.

import { Pass, Fail } from "std/fallible"
import { Json, messages, Decodable, Encodable } from "std/json"
import logging, { info } from "std/logging"

type Quantity = Int64 where >= 1 & <= 12
type Size = "small" | "large"
type Line(drink: String, size: Size, quantity: Quantity = 1)
conform Line to Encodable, Decodable
type Order(table: Int64, lines: Array<Line>)
conform Order to Encodable, Decodable

fn main() -> Int64 {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    let good: Json = { table: 4, lines: [{ drink: "mocha", size: "large" }] }
    let bad: Json = {
        table: "four",
        lines: [{ drink: "mocha", size: "huge", quantity: 40 }],
    }
    for input in [good, bad] {
        match input as Order {
            Pass(order) => info("ok: {order.encode()}")
            Fail(issues) => info("rejected: {messages(issues)}")
        }
    }
    0
}

Output

ok: {"table":4,"lines":[{"drink":"mocha","size":"large","quantity":1}]}
rejected: table: expected integer, got string; lines.0.size: expected "small" | "large", got huge; lines.0.quantity: expected integer <= 12, got 40

HTML as values§

A tag is an expression of type Node. A type becomes a component by conforming to Component and writing its view. Text and attributes are escaped when the tree is written out; there is no template language and no string building.

import logging, { info } from "std/logging"

type Drink(name: String, cents: Int64)

type Menu(title: String)

conform Menu to Component {
    fn view(children: Array<Node>) -> Node {
        <section class="menu">
            <h2>{title}</h2>
            <ul>{children}</ul>
        </section>
    }
}

fn price(cents!: Int64) -> String {
    let rest = cents % 100
    if rest < 10 { "${cents / 100}.0{rest}" } else { "${cents / 100}.{rest}" }
}

fn main() -> Int64 {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    let drinks = [
        Drink(name: "Espresso", cents: 300),
        Drink(name: "Café <crème>", cents: 450),
    ]
    let page = <Menu title="Today">
        {for drink in drinks {
            <li data-cents={drink.cents}>{drink.name} · {price(drink.cents)}</li>
        }}
    </Menu>
    info(page.html())
    0
}

Output

<section class="menu"><h2>Today</h2><ul><li data-cents="300">Espresso · $3.00</li><li data-cents="450">Café &lt;crème&gt; · $4.50</li></ul></section>

A web server§

A type whose body lists methods and paths is a router: the compiler writes its route function. serve runs it on one OS thread, a task per connection. The form is read into a type, the list is written as JSON.

import server from "std/http/server"
import { Request, Response, ok, badRequest, seeOther, htmlResponse } from "std/http"
import { Pass, Fail } from "std/fallible"
import { messages, Decodable } from "std/json"

type NoteText = String where >= 1 & <= 280
type NewNote(text: NoteText)
conform NewNote to Decodable

mut notes: Array<String> = []

type Routes {
    GET "/" -> Response {
        htmlResponse(
            <main>
                <form method="post" action="/notes">
                    <input name="text" required />
                    <button>Add</button>
                </form>
                <ol>{for note in notes { <li>{note}</li> }}</ol>
            </main>
        )
    }

    POST "/notes" (request: Request) -> Response {
        match NewNote.readForm(request.body.toString()) {
            Fail(issues) => badRequest(messages(issues))
            Pass(note) {
                notes.append(note.text)
                seeOther("/")
            }
        }
    }

    GET "/notes.json" -> Response {
        ok(Bytes.fromString(notes.encode()), "application/json")
    }
}

fn main() -> Int64 {
    match server.serve(8080, Routes().route) {
        Pass => 0
        Fail(_) => 1
    }
}

SQL§

sql"…" is a tagged string: each hole becomes a quoted SQL literal, so a value cannot change the statement. SQLite is compiled into the runtime.

import sqlite, { SqlInt, SqlText, SqlValue } from "std/sqlite"
import { Has, Not, May, Pass, Fail, Trial } from "std/fallible"
import logging, { info } from "std/logging"

type Visitor(name: String, visits: Int64)

fn show(cell!: May<SqlValue>) -> String {
    match cell {
        Not => "null"
        Has(value) {
            match value {
                SqlText(text) => text
                SqlInt(number) => "{number}"
                else => "?"
            }
        }
    }
}

fn run() -> Trial<Void, String> {
    let db = sqlite.open(":memory:")?
    db.exec(sql"CREATE TABLE visitors (name TEXT, visits INTEGER)")?
    let visitors = [
        Visitor(name: "Ada", visits: 3),
        Visitor(name: "Grace", visits: 5),
        Visitor(name: "Robert'); DROP TABLE visitors; --", visits: 1),
    ]
    for visitor in visitors {
        db.exec(sql"
            INSERT INTO visitors (name, visits)
            VALUES ({visitor.name}, {visitor.visits})
        ")?
    }
    let rows = db.query(sql"SELECT name, visits FROM visitors ORDER BY visits DESC")?
    for row in rows {
        info("{show(row.cells.get("visits"))}  {show(row.cells.get("name"))}")
    }
    Pass(Void)
}

fn main() -> Int64 {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    match run() {
        Pass => 0
        Fail(error) {
            info(error)
            1
        }
    }
}

Output

5  Grace
3  Ada
1  Robert'); DROP TABLE visitors; --

Tasks§

--> starts a call and does not wait for it. A socket operation that would block parks the task and another one runs. One OS thread, no async, no await: the same function works in a task or out of one.

import net, { Socket, createSocket } from "std/net"
import { Pass, Fail, Trial } from "std/fallible"
import logging, { info } from "std/logging"

fn listen(listener!: Socket, clients!: Int64) -> Trial<Void, String> {
    for served in 0..clients {
        let peer = listener.accept()?
        --> answer(peer)
    }
    Pass(Void)
}

fn answer(peer!: Socket) -> Trial<Void, String> {
    let request = peer.receive().toString()
    peer.sendAll(Bytes.fromString(request.toUpper()))?
    peer.close()
    Pass(Void)
}

fn ask(port!: Int64, word!: String) -> Trial<String, String> {
    let client = createSocket()?
    client.connect(port)?
    client.sendAll(Bytes.fromString(word))?
    let reply = client.receive().toString()
    client.close()
    Pass(reply)
}

fn run() -> Trial<Void, String> {
    let listener = createSocket()?
    listener.reuseAddr()?
    listener.bind(0)?
    listener.listen(16)?
    let port = listener.localPort()?
    let words = ["tasks", "park", "on", "sockets"]
    --> listen(listener, words.count)
    for word in words {
        info(ask(port, word)?)
    }
    Pass(Void)
}

fn main() -> Int64 {
    logging.toStdout()
    logging.setFormat(logging.formatPlain)
    match run() {
        Pass => 0
        Fail(error) {
            info(error)
            1
        }
    }
}

Output

TASKS
PARK
ON
SOCKETS

Calling C§

extern fn declares a C function and the compiler writes its prototype, so anything in libc (or another linked library) can be called. A type with body fields has C layout, and Address<T> passes it by pointer. This program asks the kernel its name with uname(2) and writes the answer with write(2).

## struct utsname on Linux: six 65-byte fields.
type SystemName {
    mut sysname: Array<Byte, 65>
    mut nodename: Array<Byte, 65>
    mut release: Array<Byte, 65>
    mut version: Array<Byte, 65>
    mut machine: Array<Byte, 65>
    mut domainname: Array<Byte, 65>
}

extern fn uname(name!: Address<SystemName>) -> Int32 from "c"
extern fn write(fd!: Int32, data!: Bytes, count!: UInt64) -> Int64 from "c"

fn print(text!: String) {
    let data = Bytes.fromString("{text}\n")
    write(1, data, data.count)
}

fn main() -> Int64 {
    mut name = SystemName()
    if uname(name) != 0 {
        print("uname failed")
        return 1
    }
    mut kernel = Bytes(0)
    mut index = 0
    while index < 65 and name.sysname[index] != 0 {
        kernel = kernel.insert(name.sysname[index], at: kernel.count)
        index = index + 1
    }
    print("kernel: {kernel.toString()}")
    0
}

Output

kernel: Linux

Status

Thoxa is pre-alpha. What works is what the test suite covers: each feature above has programs in tests/conformance that compile, run, and print what they should on every change, under LeakSanitizer. Not there yet:

Building

You need a Rust toolchain and a C compiler (GCC or Clang).

git clone https://github.com/moonlight-pm/thoxa
cd thoxa
cargo build -p thoxa                  # the compiler: target/rust/debug/thoxa
cargo make test                       # conformance suite, samples, unit tests
target/rust/debug/thoxa run workloads/landing/samples/types.thx

The manual covers the language, the standard library, and the tools. Problems and questions go to the issue tracker.