A memory safe, data oriented language

Quirki

A small, work-in-progress language asking one question: could fast, memory safe code also be obvious to read, and hard to get wrong? It grew out of my experience in the video game industry, where code has to run fast and bugs were (unnecessarily) plentiful.

  • One way to branch. Cases elegantly replace if, switch, optionals and error types. Conditions, enums, bools and errors all work the same way.
  • No garbage collector. Every value has one owner, so there are no pauses to tune around.
  • Errors you can't forget. Every way a call can fail is in its signature, and the compiler makes you handle it. No exceptions jumping past the code you're reading.
  • Simple concurrency. Dead simple to write, and safe: two tasks can never change the same variable.
  • Borrows from Rust, Swift, Odin, Go and Lobster. Rust's safety, Swift's readability, Odin's directness, Go's simplicity and Lobster's lightweight blocks, without the ceremony.
  • Every change is marked with <-. You never have to open a function to see what it touched.

The same four lines. Only one tells you what changed.

In a typical object oriented language you have to open each method to find out what it touches. In Quirki the call site says it.

Typical OO style
typical
world.spawn(enemy);
// changes world? enemy? both?

var e = list.last();
// a copy or a reference?

var c = e;
// a new entity, or shared with e?

var a = load(path);
// might throw. who catches it?
Quirki
quirki
world <- Spawn(enemy)
// world changes. enemy can't.

Entity e = loan GetLast(list)
// a reference, tracked by the compiler

Entity c = copy e
// a real copy. you can see it on the line.

Asset a = ? LoadAsset(path) |: fallback
// on failure, use fallback. right here.

Learn Quirki one symbol at a time

Quirki has a small set of symbols, and each one means the same thing everywhere. Each chapter introduces a symbol or two, and later chapters combine the ones you've already seen. By the end, every line of Quirki should read like a sentence.

mutation cases & return ownership & checks tasks types functions line is an error
01 / Data

A new name starts with ===

Every definition in Quirki starts with three equals signs. When you scan a file, each === marks the start of something new.

The simplest definition is a struct: a name, then its fields, each with a type and a name.

a struct
=== Hero
    Entity entity
    Weapon weapon
    Int health
    Int armorClass

That's all a struct is: data. There are no methods inside it. You'll see in a moment where the behaviour goes.

02 / Cases

Enums

When a value can be one of several things, list them with |. A weapon fires with success, or no ammo, or a jam. This kind of type is called an enum.

an enum
=== FireWeapon
    | success
    | noAmmo
    | jammed
    | overheated

A case can carry values, written in parentheses after its name:

cases with values
=== AIState
    | idle
    | patrol(Vector)
    | attack(Entity, Weapon)
    | flee(Vector)

Two shorthands. Leave out the name and the case is named by its type. Or tie each case to a fixed value with =.

named by type
=== Shape
    | (Circle)
    | (Square)
    | (Triangle)
tied to values
=== Direction
    | north = float2(0,1)
    | south = float2(0,-1)
    | east  = float2(1,0)
    | west  = float2(-1,0)

Hold on to |. It comes back in almost every chapter, and it always means the same thing: one of these.

03 / Functions

Inputs in ( ), output after |

Functions are defined with === too. The inputs go in parentheses.

=== PrintHealth(Hero hero)
    print(hero.health)

Inputs are read-only

Everything inside ( ) can be looked at but not changed. There is no const, & or mut to write. Being inside the parentheses is enough. So when you see PrintHealth(hero), you know hero comes back exactly as it went in, without opening the function.

Output after |

What a function gives back goes after a |. Read it as: DotProduct takes two Float3s and gives back a Float.

=== DotProduct(Float3 a, Float3 b) | Float

Remember, | means "one of these". It's the same symbol as in enums. Next we'll see why.

=== LoadAsset(Path path) | success(Asset) | failToLoad

LoadAsset gives back either a success with an Asset, or a failToLoad. That's how Quirki handles errors. There are no exceptions, only cases you can see in the signature.

04 / Mutation

Arrows show where data flows

Inputs inside ( ) are read-only. So how do you change something? With <-. It points into the variable that changes.

direction <- Normalize()

Several things can change at once. They are all on the left.

hero, enemy <- Battle()
the left side tells you
// The beauty of this: you can tell what changed
// just by glancing down the left side.
speed = distance / time
target = FindNearest(enemies)
hero <- MoveTowards(target, speed)
hero, target <- Battle()

Chaining

When the functions return nothing, you can chain them. They run left to right.

direction <- Normalize() <- Inverse()

No nesting

A change inside another call's arguments is not allowed. The order of changes should be obvious from reading top to bottom.

data <- Foo( thing <- Bar() )  // Error: nested mutation

The signature

In a definition, -> marks what the function changes. Now the three slots of a signature are complete, always in this order: what it reads, what it changes, what it returns.

read · change · return
=== ApplyDamage(Int amount) -> Hero hero | died | survived

// at the call site, the changed variable is on the left
hero <- ApplyDamage(amount)
05 / Matching

The same |, now after a value

You define cases with |, and you handle them with | too. Write a value, then list its cases below, each followed by : and what to do.

hulk.mood
| sleepy : hulk <- Rest()
| angry  : hulk <- Transform()

This works on any value, not only enums:

player.name
| "John" : player <- ExtraLuck()
| "Mike" : player <- Curse()

Else is an empty case

Matching an enum must cover every case. A case with no name, |:, catches everything else. It's your "else".

hulk.mood
| angry : hulk <- Transform()
|: hulk <- Rest()

Now it's time for...

Happy cases

Lots of things either work or don't. A file loads, or it doesn't. A search finds something, or nothing. Quirki makes these cases easy to write, and the happy path easy to follow.

The simplest example is a value that might be missing. You either have an asset, or you have nil:

=== MaybeAsset
    |> (Asset)
    | nil

That's it. |> is the case where things went well, and | is the one where they didn't.

A type can have more than one happy case, as long as they all carry the same type. That way you can use the value without caring which one you got:

=== LoadResult
    |> success(Asset)
    |> dummyDefault(Asset)
    | errorCode(Int)

Why mark the happy case?

Because it lets one small idea do the work of several. Optionals, error types and plain true/false results all become the same thing: a type where some cases mean "it worked". That's one thing to learn instead of three, and we hope it stays out of your way.

? asks: is this value a happy case? If it is, you get the value inside.

Say Load gives back a LoadResult. One look at LoadResult shows it has happy cases, so you know straight away you can unwrap it, right at the call:

? loadResult as asset :
    Draw(asset)    // only runs when it loaded

No error codes to check by hand, and no way to use the asset when it didn't load.

Happy, or else

After a ?, the else symbol |: simply reads as "if it didn't work". Use it to give a fallback value:

Asset asset = ? Load(path) |: defaultTexture

Bools work the same way, since true is their happy case. A single check reads like an if, and the same shape works as an expression:

? hero.isAlive : hero <- GetUp()

Int steps = ? farOff : 10 |: 0

Guard against failure

Or leave the function right there. Put => after |: to return from the function, and everything below the guard can trust that the value exists.

=== DrawIcon(Path path) | drawn | failed

    Asset asset = ? Load(path) |: => .failed

    // from here on, asset is always there
    Draw(asset)
    => .drawn

The failure is handled once, at the top, and the rest of the function only deals with the happy path.

Need the error?

Name the unhappy value with | as name. Every path must end in a happy value or a =>.

Asset asset = ? Load(path) | as failure :
    print(failure.name)
    => .failed

Every case, by name

Drop the ? for an exhaustive match, where every case must be handled. (=) means "the value inside is the result", and (.) ignores it. In Quirki a dot always means "nothing" or "ignore".

Asset asset = Load(path)
| success(=)
| dummyDefault(=)
| errorCode(.) : => .failed

Insist with !

! unwraps and crashes if the value isn't happy. In Quirki ! is only ever about errors, which is why "not equal" is written =/=. A nice side effect: searching your project for ! should give you a good list of the places that can crash.

// unwrap an optional, or crash if it's nil
MaybeAsset maybe = FindAsset(name)
Asset asset = maybe!

// or straight from a call
Draw( Load(path)! )

Conditions are happy cases too

The same idea covers plain conditions. In Quirki, a Bool is defined like this:

=== Bool
    |> true
    | false

true is the happy case, so ? works on any condition too.

Happy cases in a signature

You don't always need a separate type. Happy cases can be written straight into a function's signature:

=== LoadAsset(Path path) |> success(Asset) | failToLoad
Rule

A match that produces a value needs a value or a => in every case.

07 / Concurrency

Easy concurrency, built in

Concurrency in Quirki is designed to be easy to write and easy to reason about.
# starts a task
--- awaits them

The most common case: update every item at the same time, then wait for all of them.

one task per item
Each(entities) as e:
    #: e <- Update()
---

Tasks can also have names, and be nested:

tasks and a barrier
#load:
    #file:
        path <- Format()
        LoadFile(path)

    #texture: LoadTexture()
---

// Results are shaped like the task tree
UseTexture(load.texture)

Before the barrier, a task's name stands for the running task, so you can't read it yet. After ---, it's just data.

#texture: LoadTexture()
Use(texture)      // Error: texture is not done yet
---
Use(texture)      // OK: it's plain data now

A task can have its own barrier inside:

#task:
    #a: A()
    #b: B()
    ---
    #c: Use(a, b)

Race, types and lanes

first one wins
#winner (race):
    #: LoadCache()
    #: Network()
    #: Sleep(5.0)
explicit type
#Mesh mesh: LoadMesh()
pick a thread
Lane physics:
    Each(entities) as e :
        #: e <- PhysicsUpdate()
---

Collecting results into a list

Parallel tasks may never change the same variable, so tasks don't append to a shared list. The loop appends the pending tasks, and each task only returns its value. After --- it's a plain list, in loop order.

#Texture[] textures

Each(paths) as path:
    textures <- Append( #: LoadTexture(path) )
---
UseTextures(textures)     // a Texture[] now

Writing to fixed, separate slots is fine too:

Int n = 12
Int[n] values

Each(from: 0, to: n) as i :
    #: values[i] = CalculateSomething(i)
08 / Ownership

One owner per value

Every value has exactly one owner. Assigning it to another variable moves it, and the old name stops working. A copy is always written out.

move
a = b

Use(a)  // OK
Use(b)  // Error: b was taken
copy
a = copy b

Use(a)  // OK
Use(b)  // OK: both remain valid

Inputs in ( ) are only borrowed by the call. To hand a value over for good, write take, both in the signature and at the call:

=== Insert(take Item item) -> Inventory inventory

hero.inventory <- Insert(take item)
Use(item)  // Error: item now lives in the inventory
09 / Refs & loans

References without lifetime annotations

A function can return a ref: access to a value it doesn't own. The caller then chooses to loan it (keep the access) or copy it.

=== GetLast(Entity[] entities) | ref Entity
    => entities[entities.length - 1]

Entity e = GetLast(entities)        // Error: this is a reference
Entity e = loan GetLast(entities)   // OK
Entity e = copy GetLast(entities)   // OK

A loan works like the value, with two exceptions:

Use(e)                 // OK
e <- Mutate()          // OK
SomeFunction(take e)   // Error: borrowed values can't be taken
e = NewEntity()        // Error: loans can't be reassigned

The loan rule

While a loan is alive, its original is locked. The loan ends automatically after its last use.

Entity e = loan GetLast(entities)
entities <- Clear()      // Error: e still points into entities
Use(e)
entities <- Clear()      // OK: e is not used anymore

Without this rule, the loan could point at memory that's gone:

Entity e = loan GetLast(entities)
entities <- Clear()      // the list frees its memory
e <- Mutate()            // writes into freed memory

Every change is written with <-, so the compiler can check this without a separate "mutable borrow" type.

Changing through a loan

Changing a loan counts as changing its original. So you may only change e where you're allowed to change entities. One GetLast works for both reading and writing.

read-only list
=== CountAlive(Entity[] entities) | Int
    Entity e = loan GetLast(entities)
    e <- Kill()     // Error: entities is read-only
mutable list
=== KillLast() -> Entity[] entities
    Entity e = loan GetLast(entities)
    e <- Kill()     // OK: entities may change

Two rules that remove lifetime syntax

Rule

A ref is never stored in a struct.

Refs only live in locals, so a ref simply lasts until the end of its block. Store an index or id instead and look it up when you need it.

=== Player
    ref Entity target      // Error: refs can't be stored
    Int targetIndex        // OK
Rule

A returned ref must point into one of the arguments.

Then the compiler always knows what the ref borrows from. With several arguments, it borrows from all of them.

=== Make() | ref Entity
    Entity e = NewEntity()
    => e                   // Error: e dies when Make returns

=== Bigger(Entity a, Entity b) | ref Entity

Entity big = loan Bigger(a, b)
a <- Heal(10)              // Error: big may point into a
Use(big)

Read-only inputs accept both owned and borrowed values, so you never write two versions of a function.

10 / Blocks

Pass code to functions

You've already used Each(entities) as e:. Your own functions can take a block of code the same way, and calling them looks built in.

=== F = () -> Entity                   // a function type
=== G = (Float dt) -> Entity | Bool     // same slots as a definition

=== ForEachAlive(Entity[] entities, F action)
    Each(entities) as entity:
        ? entity.isAlive : entity <- action()

// Calling it
ForEachAlive(entities) as entity:
    entity <- Heal(10)
Rule 1

Functions are only passed as parameters.

They can't be stored, assigned or returned. A block only runs during the call, so it just borrows what it uses. Where you'd store a callback, use an enum and a match.

Rule 2

What a block uses counts as extra arguments of the call.

The usual rules about passing a variable twice then apply.

ForEachAlive(entities) as e:
    e <- Heal(10)              // OK: its own element
    count <- Add(1)            // OK: only the block touches count
    print(entities.length)     // OK: reading is fine
    entities <- Clear()        // Error: entities is in use by the call
    entities[0] <- Kill()      // Error: same reason
Rule 3

#F marks a block that may run as tasks.

It's the task symbol from the Concurrency chapter. Such a block can change what it's given and only read everything else.

=== UpdateAll(Entity[] entities, #F action)

UpdateAll(entities) as e:
    e <- Move(speed)           // OK
    count <- Add(1)            // Error: this block may run as tasks

To count in parallel, let each task return a value and add them up after the barrier:

#Int[] hits
Each(entities) as e:
    hits <- Append( #: ? e.isAlive : 1 |: 0 )
---
count = Sum(hits)
11 / Small rules

A few things that keep code honest

Do nothing with |:.

Add a dot to the else case and it means "anything else: do nothing". It's the same dot as in (.): nothing, or ignore. It only works in matches used as statements, since a match that produces a value needs a value in every case.

hulk.mood
| angry : hulk <- Transform()
|:.

Never the same variable twice

One call can't see the same variable through two names. This removes a whole class of aliasing bugs and helps the optimizer.

func(a, a)       // Error
a, a <- func()   // Error
a <- func(a)     // Error: copy a to use it as an input

No cases after a change that returns nothing

Cases after state <- ChangeState() would look like they check the new state. They don't, so Quirki stops you. To check state, match on it on its own line.

state <- ChangeState()   // Error: nothing to match on
| ok
| fail

state <- ChangeState()
state                    // OK: match on state itself
| ok
| fail

! is only for errors

Not-equal is =/=. Flip a bool with Invert(flag), or in place with flag <- Invert().

? hero.health =/= 0 : hero <- Rest()
isOpen <- Invert()

Matching on true

Put ? in front and each | becomes a condition, tested in order. |: is still the else.

? x >= 3 : inventory <- UseItem(item, 2)
| x >= 1 : inventory <- UseItem(item, 1)
|: print("no items left!")