Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This book is the definitive book on the Quokka programming language and development toolkit.

What is Quokka programming language?

Quokka is a programming language designed to programs which target the Nintendo1 Game Boy2 or Game Boy Color. It blends high level language concepts with low level assembly language to meet the needs developing for the constrained hardware.

Why use Quokka?

The truth is that if your primary desire is to develop a homebrew video game for the Game Boy or Game Boy Color, then you would be better served by using RGBDS and programming in assembly. RGBDS is a comphrensive suite of tools developed and hardened over decade. In contrast, Quokka is still in the early stages of development, and is likely buggy and incomplete.

If your goal is to learn, understand and use a programming language designed for a highly constrained system, then Quokka might be what you are looking for.

How to read this book

This book consists of following sections:

  • User guide: A practical guide for using the Quokka
  • Reference: The specification for the Quokka programming language and manual for the development toolkit

The user guide assumes that you’re reading it sequentially from front to back as later chapters build on concepts in earlier chapters. In contract, the reference does not assume it is being read sequentially, with each chapter being cross-referencing other chapters to elaborate on related concepts.


  1. This project is not endorsed by or associated with Nintendo. ↩

  2. Game Boy & Game Boy Color are a registered trademarks. ↩

Getting started

This part of the book takes you from nothing to a Game Boy ROM, compiled by Quokka, that shows a picture you drew yourself. Work through the chapters in order:

  1. Installation: install RGBDS, which Quokka uses to link ROMs, and then install the quokka compiler, either from a pre-built release or by building it from source.
  2. Hello, Quokka!: a tutorial that turns a 160×144 pixel PNG into Game Boy tile data and writes a Quokka program to display it. Along the way it covers how the Game Boy draws its background, and the Quokka globals, constants, arrays and loops used to drive it.

Once you have finished the tutorial, go to the reference. It gives the full details of every part of the language, such as the types, attributes and expressions that the tutorial only touches on. The reference doesn’t need to be read in order, so jump to whatever you need.

You don’t need to know Game Boy assembly to follow along, but Quokka works close to the hardware. The Pan Docs and the GB ASM tutorial are both good companions for learning how the Game Boy itself works.

Installation

Installing Quokka takes two steps:

  1. Install RGBDS, which Quokka uses to link ROMs.
  2. Install the quokka compiler, either from a pre-built release or by building it from source.

Prerequisite: RGBDS

Quokka compiles your program into an object file and then hands it to RGBDS, the standard Game Boy development toolchain, to finish the ROM:

  • rgblink links the object file into a ROM.
  • rgbfix fills in the ROM’s header (the Nintendo logo and checksums), which a real Game Boy checks before running a game.

The Hello, Quokka! tutorial also uses rgbgfx to convert images into Game Boy graphics.

All three tools come with RGBDS, and they must be on your PATH. Quokka is tested against RGBDS v1.0.4. Older versions may not be able to read the object files Quokka produces.

The RGBDS installation guide covers every platform. Briefly:

  • macOS: brew install rgbds
  • Linux: some distributions package RGBDS, but the packaged version is often old. Check its version, and if it is older than v1.0.4, use a pre-built binary from the RGBDS releases or build it from source as the installation guide describes.

Check that the tools are on your PATH and are recent enough:

$ rgblink --version
rgblink v1.0.4

Installing a pre-built release

Each Quokka release provides pre-built binaries for:

PlatformTarget
macOS on Apple siliconaarch64-apple-darwin
Linux on x86-64x86_64-unknown-linux-musl
Linux on 64-bit ARMaarch64-unknown-linux-musl

The Linux binaries are statically linked, so they work on any distribution. On any other platform (such as an Intel Mac or Windows), build Quokka from source.

Go to the latest release and download the quokka-<version>-<target>.tar.gz archive for your platform, along with its .sha256 checksum file. For example, for version v0.3.0 on an Apple silicon Mac:

VERSION=v0.3.0
TARGET=aarch64-apple-darwin
curl -LO "https://github.com/jhinch/quokka-lang/releases/download/$VERSION/quokka-$VERSION-$TARGET.tar.gz"
curl -LO "https://github.com/jhinch/quokka-lang/releases/download/$VERSION/quokka-$VERSION-$TARGET.tar.gz.sha256"

Verify the download and extract it:

shasum -a 256 -c "quokka-$VERSION-$TARGET.tar.gz.sha256"
tar -xzf "quokka-$VERSION-$TARGET.tar.gz"
cd "quokka-$VERSION-$TARGET"

The extracted directory contains the quokka binary, along with the license and README.

macOS: removing the quarantine attribute

The macOS binaries are not yet signed. If you downloaded the archive with a web browser, macOS quarantines it, and Gatekeeper refuses to run quokka with a message saying it “cannot be opened because the developer cannot be verified”. Removing the quarantine attribute from the binary lets it run:

xattr -d com.apple.quarantine ./quokka

curl doesn’t set the attribute, so if you downloaded the archive with the commands above, xattr reports that there is no such attribute and you can skip this step.

Putting quokka on your PATH

Move the binary into a directory on your PATH, for example:

mkdir -p ~/.local/bin
mv quokka ~/.local/bin/

If ~/.local/bin isn’t already on your PATH, add it in your shell’s configuration file (such as ~/.zshrc or ~/.bashrc):

export PATH="$HOME/.local/bin:$PATH"

Then check that the installation works.

Building from source

Building from source works on any platform with a Rust toolchain. Quokka uses the Rust 2024 edition, so you need Rust 1.85 or newer. The easiest way to get it is through rustup.

cargo can build and install the quokka binary straight from the repository:

cargo install --locked --git https://github.com/jhinch/quokka-lang quokka-lang

Or, to build from a local checkout (for example, if you plan to change the compiler):

git clone https://github.com/jhinch/quokka-lang.git
cd quokka-lang
cargo install --locked --path .

Either way, cargo installs quokka into ~/.cargo/bin, which rustup adds to your PATH.

You don’t need the repository’s SameBoy submodule to build the compiler. Only Quokka’s own emulator test suite uses it.

Checking the installation

Check that quokka runs:

$ quokka --help
Usage: quokka [OPTIONS] <COMMAND>

Commands:
  build
  lsp
  help   Print this message or the help of the given subcommand(s)
...

With both Quokka and RGBDS installed, you’re ready to build your first ROM in Hello, Quokka!.

Hello, Quokka!

In this tutorial you’ll write a Quokka program that fills the Game Boy’s screen with a picture. Instead of using ready-made graphics, you’ll start from an ordinary PNG and go through every step needed to get it on screen:

  1. Convert the PNG into Game Boy tile data with rgbgfx.
  2. Dump that data as bytes you can paste into Quokka source code.
  3. Write a program that copies the bytes into video memory and turns on the screen.
  4. Build the ROM and run it in an emulator.

The program is based on the “Hello, World!” program from the GB ASM tutorial, which is also available as a Quokka program in the repository at examples/hello_world.q.

Before starting, make sure Quokka and RGBDS are installed.

Setting up

Create a directory for the project:

mkdir hello-quokka
cd hello-quokka

You’ll need a 160×144 pixel image, which is the size of the Game Boy’s screen. You can draw your own (see Image requirements) or download the one used in this tutorial, hello-quokka.png, into the project directory:

How the Game Boy draws the background

The Game Boy doesn’t have a framebuffer you can write individual pixels into. Instead, the picture processing unit (PPU) builds the background out of three pieces of data:

  • Tiles: 8×8 pixel images. Each pixel is one of four colors, numbered 0 to 3, so a pixel needs two bits. A tile is stored as 16 bytes, two bytes per row of 8 pixels. The first byte of a row holds the low bit of each pixel’s color and the second byte holds the high bit, with the leftmost pixel in the most significant bit. This is called the 2bpp (two bits per pixel) format.
  • The tilemap: a 32×32 grid of bytes, starting at address 0x9800 in video memory (VRAM). Each byte selects which tile to draw in that cell. The background is 256×256 pixels, but the screen only shows a 160×144 pixel window of it, which is the top-left 20×18 tiles.
  • The palette: the color numbers in a tile don’t specify a shade directly. The background palette register BGP maps each color number to one of the four shades the screen can display, from white to black.

The background in this tutorial reads its tiles from the block that starts at 0x9000. In that mode, tile number 0 is at 0x9000, tile 1 at 0x9010, and so on. For more details, see the Pan Docs.

So drawing the picture means cutting the image into 8×8 tiles, storing each distinct tile once, and filling the tilemap with the tile number for each cell of the screen. That’s exactly what rgbgfx does for you.

Converting the image with rgbgfx

Run rgbgfx on the image:

rgbgfx -c '#ffffff,#aaaaaa,#555555,#000000' -u -o hello-quokka.2bpp -t hello-quokka.tilemap hello-quokka.png

The options mean:

  • -c '#ffffff,#aaaaaa,#555555,#000000' sets which image color becomes which color number: white is 0, light gray 1, dark gray 2 and black 3. Without it, rgbgfx chooses the order itself, and the picture could come out with its shades swapped. Fixing the order means the palette can map each color number straight to the matching shade.
  • -u stores each distinct tile only once. A 160×144 image is 20 × 18 = 360 tiles, but most of them are repeats (the blank background is the same tile over and over), so the example image needs only 90 tiles.
  • -o hello-quokka.2bpp writes the tile data, in the 2bpp format, to hello-quokka.2bpp.
  • -t hello-quokka.tilemap writes the tilemap, one byte per tile, to hello-quokka.tilemap.

Check the sizes of the two files:

$ wc -c hello-quokka.2bpp hello-quokka.tilemap
    1440 hello-quokka.2bpp
     360 hello-quokka.tilemap
    1800 total

The tile data is 90 tiles × 16 bytes = 1440 bytes. The tilemap is 20 × 18 = 360 bytes, one byte for each tile on the screen. You’ll need both sizes when declaring the arrays in Quokka.

Image requirements

If you draw your own image, it must:

  • be 160×144 pixels, so that it fills the screen exactly;
  • use at most the four colors listed in the -c option (pure black and white are fine);
  • contain at most 128 distinct tiles. With the tile block at 0x9000, tiles 0 to 127 sit between 0x9000 and 0x97FF. Copying any more would run into the tilemap at 0x9800. Large areas of one solid color keep the count down. To find the count, divide the size of the .2bpp file by 16.

Turning the bytes into Quokka arrays

Quokka doesn’t have a way to include a binary file directly, so the tile data and tilemap go into the program as array constants. hexdump can print a file’s bytes in exactly the syntax a Quokka array expects.

The tile data

Print the tile data as one tile (16 bytes) per line:

hexdump -v -e '16/1 "0x%02x, " "\n"' hello-quokka.2bpp

The format string after -e is applied over and over until the file runs out:

  • 16/1 "0x%02x, " formats 16 units of 1 byte each, printing each as a two-digit hexadecimal number followed by a comma.
  • "\n" ends the line.

The -v option matters. By default, hexdump replaces repeated lines with a single *, which would silently drop tiles that happen to be identical to the one before.

The output starts with the blank tile, followed by the top of the quokka’s left ear:

0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x7e, 0x71, 0x7e, 0x71, 0x7e, 0x71, 0x7f, 0x70, 0x7f, 0x70,
...

Read the second line two bytes at a time. Row 0 of that tile is 0x0f, 0x0f: the first four pixels have neither bit set, so they are color 0 (white), and the last four have both their low and high bits set, so they are color 3 (black), the outline of the ear. Row 3 is 0x7e, 0x71, which mixes all four colors: the first pixel is white, the next three are black, the next three have only their low bit set, so they are color 1 (light gray), and the last pixel has only its high bit set, so it is color 2 (dark gray).

The tilemap

The tilemap from rgbgfx has 20 bytes per row, one for each tile across the screen, but VRAM’s tilemap is 32 tiles wide. Each row needs another 12 bytes to fill out the rest of the row, which is off screen. hexdump can add those while it formats the bytes:

hexdump -v -e '20/1 "0x%02x, " " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n"' hello-quokka.tilemap

This time each line formats 20 bytes and then prints twelve 0 entries. Those cells are never visible, so it doesn’t matter which tile they point at. The output is 18 lines of 32 entries, 576 bytes in all:

0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
...
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x08, 0x09, 0x0c, 0x0d, 0x0c, 0x0e, 0x0f, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
...

You can see the picture’s layout in the numbers. The top six rows of tiles are blank (tile 0). The seventh row starts with a blank tile, then tiles 1 to 6, which are the tops of the quokka’s ears, and then the top of “QUOKKA”. The two “K“s are identical, so tiles 8 and 9 appear twice in a row, which is the -u option at work.

Writing the program

Create a file named hello_quokka.q. The program has three parts: names for the hardware registers and memory it uses, the graphics data, and a main function that puts them together.

Hardware registers

The Game Boy is controlled by writing to hardware registers at fixed memory addresses. In Quokka, you give a register a name by declaring a global with the address attribute, which places the global at that exact address. Reading or writing the global then reads or writes the register:

// Audio master control. Writing 0 turns the audio hardware off.
#[address = 0xFF26]
global rAUDENA: u8;
const AUDIO_OFF: u8 = 0;

// The line the LCD is currently drawing. Lines 144 to 153 are the vertical blanking period.
#[address = 0xFF44]
global rLY: u8;
const LY_VBLANK: u8 = 144;

// LCD control. Bit 7 turns the LCD on and bit 0 turns the background on.
#[address = 0xFF40]
global rLCDC: u8;
const LCDC_OFF: u8 = 0b0000_0000;
const LCDC_ON: u8 = 0b1000_0000;
const LCDC_BG_ON: u8 = 0b0000_0001;

// Background palette. Bits 1-0 set the shade for color 0, bits 3-2 for color 1, and so on.
#[address = 0xFF47]
global rBGP: u8;
const BG_PALETTE: u8 = 0b1110_0100;

The constants give names to the values written to the registers. Quokka substitutes a constant’s value wherever the constant is used, so they cost nothing at runtime.

BG_PALETTE is 0b11_10_01_00. Reading it in pairs of bits from the right, color 0 gets shade 0 (white), color 1 gets shade 1 (light gray), color 2 gets shade 2 (dark gray) and color 3 gets shade 3 (black). Because the -c option put the image’s colors in the same order, each pixel appears in its original shade.

Video memory

The same address attribute can place an array over a region of memory. These two globals cover the parts of VRAM that the program fills, with the sizes you measured earlier:

#[address = 0x9000]
global BG_TILES: [u8; 1440];
#[address = 0x9800]
global BG_TILEMAP: [u8; 576];

The graphics data

Next, add two array constants and paste the hexdump output between the brackets:

const TILES: [u8; 1440] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x7e, 0x71, 0x7e, 0x71, 0x7e, 0x71, 0x7f, 0x70, 0x7f, 0x70,
    // ... the rest of the hexdump output for hello-quokka.2bpp
];
const TILEMAP: [u8; 576] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    // ... the rest of the hexdump output for hello-quokka.tilemap
];

Quokka allows a trailing comma after the last item, so the output can be pasted in as is. The array length in the type must match the number of items exactly. If it doesn’t, the compiler reports an error, which is a useful check that nothing was lost when copying.

Large constants like these are stored in the ROM, so they don’t use any of the Game Boy’s limited RAM.

The main function

A Quokka program starts at its main function:

fn main() {
    // Turn the audio off, we won't be using it
    rAUDENA = AUDIO_OFF;

    // Wait for vblank, as the LCD must only be turned off during vblank
    loop {
        if rLY >= LY_VBLANK then {
            break;
        }
    }
    // Turn the LCD off so we can freely write to VRAM
    rLCDC = LCDC_OFF;

    // Copy the tiles and the tilemap into VRAM
    BG_TILES = TILES;
    BG_TILEMAP = TILEMAP;

    // Turn the LCD back on with the background enabled
    rLCDC = LCDC_ON | LCDC_BG_ON;
    // Set the background palette
    rBGP = BG_PALETTE;
}

Step by step:

  1. Turn the audio off. The program doesn’t play any sound, so there’s no reason to leave the audio hardware running.
  2. Wait for vertical blanking. While the PPU is drawing the screen, it has VRAM to itself, and the CPU can’t read or write it reliably. Copying 2016 bytes takes far longer than the short gap between frames, so the program turns the LCD off for the copy instead. The LCD may only be turned off during the vertical blanking period (“vblank”), because turning it off at any other time can damage a real Game Boy’s screen. The loop keeps reading rLY until the LCD reaches line 144, which is where vblank starts, and then breaks out.
  3. Turn the LCD off. VRAM can now be accessed freely.
  4. Copy the tiles and the tilemap. Assigning a whole array to another array of the same type copies every element. This is a bulk copy, and the compiler generates the copy loop for you. Each array constant has exactly the same type as the VRAM global it’s copied into, which is another reason the array lengths have to match the file sizes.
  5. Turn the LCD on with the background enabled, using | to combine the two flags.
  6. Set the palette. This is safe to do straight away, because the LCD always starts drawing from the top of a new frame when it’s turned on.

When main returns, the program has nothing left to do and the Game Boy idles, still showing the picture.

The complete program

Put together, hello_quokka.q looks like this, with the graphics data shortened:

#[address = 0xFF26]
global rAUDENA: u8;
const AUDIO_OFF: u8 = 0;

#[address = 0xFF44]
global rLY: u8;
const LY_VBLANK: u8 = 144;

#[address = 0xFF40]
global rLCDC: u8;
const LCDC_OFF: u8 = 0b0000_0000;
const LCDC_ON: u8 = 0b1000_0000;
const LCDC_BG_ON: u8 = 0b0000_0001;

#[address = 0xFF47]
global rBGP: u8;
const BG_PALETTE: u8 = 0b1110_0100;

#[address = 0x9000]
global BG_TILES: [u8; 1440];
#[address = 0x9800]
global BG_TILEMAP: [u8; 576];

const TILES: [u8; 1440] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // ...
];
const TILEMAP: [u8; 576] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    // ...
];

fn main() {
    rAUDENA = AUDIO_OFF;

    loop {
        if rLY >= LY_VBLANK then {
            break;
        }
    }
    rLCDC = LCDC_OFF;

    BG_TILES = TILES;
    BG_TILEMAP = TILEMAP;

    rLCDC = LCDC_ON | LCDC_BG_ON;
    rBGP = BG_PALETTE;
}

The full program, with all of the graphics data for the example image, is in the repository at examples/hello_quokka.q.

Building and running

Compile the program:

quokka build hello_quokka.q

Quokka writes its output to a build directory next to the source file:

  • build/hello_quokka.gb: the ROM
  • build/hello_quokka.obj: the object file passed to rgblink
  • build/hello_quokka.sym: the symbol file from rgblink, which many emulators’ debuggers can load to show names instead of addresses

Open build/hello_quokka.gb in a Game Boy emulator, such as SameBoy, Emulicious or BGB. After the boot logo, you should see your picture.

If the picture looks wrong:

  • Shades are swapped or inverted: check the -c option given to rgbgfx and the value of BG_PALETTE.
  • The picture is scrambled or shifted: check that both hexdump commands included -v, and that the tilemap rows were padded to 32 entries.
  • The compiler reports that an array has the wrong length: some of the hexdump output is missing, or the array type doesn’t match the file sizes from wc -c.

Next steps

Try it with an image of your own. Every image follows the same steps. Only the array lengths change to match the new file sizes.

From here, the reference describes everything Quokka can do, including structs, functions and the full set of operators.

Lexical Structure

Lexical analysis (“lexing”) is the process of converting a stream of characters in a source file into stream of tokens.

whitespace and comments serve only to separate tokens within the input stream and have no semantic significance.

Source encoding

Before lexing can occur, a source file is decoded as a sequence of Unicode characters encoded in UTF-8.

Tokens

Keywords

Keyword             =   StandardKeyword
                    ;
Reserved            =   Keyword
                    |   UnusedReserved
                    ;
StandardKeyword     =   "as" | "const" | "else" | "fn"
                    |   "global" | "if" | "let" | "loop"
                    |   "struct" | "then" | "yield" | "break"
                    |   "return" | "continue" | "breakpoint"
                    ;
UnusedReserved      =   "while" | "do" | "match" | "case"
                    |   "enum" | "false" | "true" | "for" | "switch"
                    |   "in" | "void" | "to" | "mod" | "root"
                    ;

Identifiers

Identifier              = IdentifierOrReserved - Reserved
                        ;
IdentifierOrReserved    = ( XIDStart | "_" ) , { XIDContinue }
                        ;
XIDStart                = ? as define in https://www.unicode.org/reports/tr31/tr31-41.html ?
                        ;
XIDContinue             = ? as define in https://www.unicode.org/reports/tr31/tr31-41.html ?
                        ;

Identifiers follow the Unicode Identifier Standard with the one addition that the first character can be an underscore (_).

Identifiers may not be a reserved word including keywords and unused reserved words.

Literals

Number literals

NumberLiteral   =   DecimalNumber
                |   BinaryNumber
                |   OctalNumber
                |   HexNumber
                ;

DecimalNumber   =   DecimalDigit , { DecimalDigit | "_" }
                ;
BinaryNumber    =   "0b" , { BinaryDigit | "_" } , BinaryDigit , { BinaryDigit | "_" }
                ;
OctalNumber     =   "0o" , { OctalDigit | "_" } , OctalDigit , { OctalDigit | "_" }
                ;
HexNumber       =   "0x" , { HexDigit | "_" } , HexDigit , { HexDigit | "_" }             
                ;
BinaryDigit     =   "0" | "1"
                ;
OctalDigit      =   "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7"
                ;
DecimalDigit    =   "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
                ;
HexDigit        =   "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" 
                |   "a" | "b" | "c" | "d" | "e" | "f" 
                |   "A" | "B" | "C" | "D" | "E" | "F"
                ;

Separators

  • { and }
  • [ and ]
  • ( and )
  • ,
  • :
  • ;
  • ->
  • #

Operators

  • =
  • + and -
  • += and -=
  • || and &&
  • |, & and ^
  • |=, &= and ^=
  • ==, !=, <, <=, >= and >
  • !
  • <<, >>, <% and >%
  • .

Comments

Comment =     "//" , { ? Any Unicode character ? - ? LF ? } , ( ? LF ? | ? EOF ? )
        ;

Whitespace

Whitespace  =   ? SP U+0020 ?
            |   ? LF U+000A ?
            |   ? FF U+000C ?
            |   ? CR U+000D ?
            |   ? TAB U+0009 ?
            ;

Source files

A collection of 1 or more source files describe a program, the unit of compilation for Quokka. When compiled, a program will produce a binary executable (a “ROM”).

Source file

SourceFile =   ? EOF ?
           |   Item , { Item } , ? EOF ?
           ;

Entry file

The entry file is a special source file and the only mandatory file required for a Quokka program. It defines the root module. The root module must contain the entrypoint function of the program. There is exactly one entrypoint function for a program. Any other number of entrypoint functions will result in a compilation error.

In addition to the entrypoint function, the entry file defines the zero or more program attributes. Program attributes apply to the entire program rather than a single item.

The entry file is typically named main.q and placed within the src/ directory from the project’s root directory.

Entrypoint function

The entrypoint function defines the code which will be executed immediately proceeding the boot ROM and the startup code. The entrypoint function must contain zero arguments.

fn main() {
    // program goes here
}

Warning

Requires custom-entrypoint preview feature enabled.

The default entrypoint function is named main. This can be customized using the #[entrypoint] attribute

#[entrypoint]
fn my_entrypoint() {
    // program goes here
}

The entrypoint function is resolved using the following steps:

  1. Find all functions within the program with an #[entrypoint] attribute.
  2. A compilation error occurs there is more than one function annotated with the #[entrypoint] attribute or there is a function annotated with the #[entrypoint] attribute outside the root module
  3. If no function is annotated with the #[entrypoint] attribute, find a function called main in the root module.

Startup code

The startup code are additional instructions added to the resulting ROM which allows for the entrypoint function to behave like a regular quokka function. The exact instructions are unspecified.

Items

Item        =   SimpleItem
            |   Attribute , { Attribute } , SimpleItem
            ;
SimpleItem  =   ConstItem
            |   GlobalItem
            |   Struct
            |   Function
            ;

Global items

GlobalItem  =   "global" , Identifier , ":" , TypeUse , ";"
            ;
global data: u8;

A global represents a portion of memory which is read/write. Its value is not known as compile time and can only be accessed at runtime. Quokka does not support initializing globals like it does for local variables or for constant declarations. Values much be initialized at runtime manually within code or point to specific memory mapped I/O addresses.

Using specific regions of memory

By default, when a global is declared, it will be allocated statically to the general purpose RAM (WRAM) where it can fit. However, the region and address attributes can be used to access other regions of memory such as video RAM, Object Attribute Memory (OAM), I/O registers, and High RAM.

// P1/JOYP register - See https://gbdev.io/pandocs/Joypad_Input.html for details
#[address = 0xFF00]
global JOYPAD: u8;

#[region = oam]
global SPRITES: [Sprite; 40];

struct Sprite {
    y: u8,
    x: u8,
    tile_index: u8,
    flags: u8,
}
  • address (u16) - The starting address of the global. Defaults to the compiler automatically choosing.
  • region - Specifies the region the global is in. Must be one of the following values:
    • auto (default) - The compiler automatically places the data in WRAM0 or WRAMX memory
    • wram0 - Working RAM
    • wramx - Working (banked) RAM
    • vram - Video RAM
    • hram - High RAM
    • sram - Save RAM
    • oam - Object Attribute Memory

Overlapping addresses

Global declarations can overlap the same underlying memory. The default whether this is permitted depends on the region of memory it points to. Working RAM, save RAM and High RAM do not permit overlaps by default, but I/O registers, Video RAM and OAM do.

Const items

ConstItem   =   "const" , Identifier , ":" , TypeUse , "=" , Expression , ";"
            ;
const data: u8 = 1;

A constant represents a value known to the compiler which doesn’t change. Constant declarations must include an expression which, when evaluated, will result in a value. The expression is evaluated at compile time and cannot rely on runtime items such as global variables or functions.

Inlining

The compiler may inline constant values into their uses. Constants which are still referenced at runtime will be be stored in read only memory (ROM) and loaded when used.

Using specific regions of memory

By default, when a constant is retained at runtime, it will be placed within the ROM0 region at compiler chosen address. However, the region and address attributes can be used place the constant in a different region of read only memory. If the address is specified, the constant will be written to read only memory at that address regardless of whether it is used or not.

Structs

Struct              =   "struct" , Identifier , "{" , [ StructFields ] , "}"
                    ;
StructFields        =   StructField , { "," , StructField } , [ "," ]
                    ;
StructField         =   SimpleStructField
                    |   Attribute , { Attribute } , SimpleStructField
                    ;
SimpleStructField   =   Identifier , ":" , TypeUse
                    ;
struct Name {
    field: u8,
}

Padding/Aignment

Structs will automatically align each field to a new byte with other bits as padding.

Additional padding can also be defined using fields with _ as their name. Padding fields must be an unsigned int. Multiple padding fields can be defined.

Warning

This example uses u2, which requires the narrow-int preview feature enabled.

// 32-bit struct
struct Padded {
    one: u2, // bit 0-1 used, bit 2-7 padding
    _: u8, // bit 8-15 padding 
    _: u8, // bit 26-23 padding
    two: u8, // bit 24-31 used
}

Functions

Function    =   "fn" , Identifier , "(" , ")" , [ "->" , TypeUse ] , BlockExpression
            ;
fn this_function() {
}

fn that_function() -> u8 {
    return 1;
}

Placing a function at a specific address

By default, a function is placed wherever the linker finds room for it. The region and address attributes pin a function to a specific location in ROM instead, the same way they do for const items.

#[address = 0x0150]
fn checkpoint() {}
  • address (u16) - The starting address of the function. Defaults to the compiler automatically choosing.
  • region - Specifies the ROM region the function is placed in. Must be one of the following values:
    • auto (default) - The compiler automatically chooses rom0 or romx based on address
    • rom0 - Fixed (bank 0) ROM
    • romx - Banked ROM

A function’s address must not overlap the cartridge header ($0100-$014F), which is always reserved by the compiler; doing so is a compilation error.

Expressions

Expression              = ExpressionWithoutBlock
                        | ExpressionWithBlock
                        ;
ExpressionWithBlock     = BlockExpression
                        | IfExpressionWithBlock
                        | LoopExpression
                        ;
ExpressionWithoutBlock  = GroupedExpression
                        | IfExpressionWithoutBlock
                        | LiteralExpression
                        | OperatorExpression
                        | PlaceExpression
                        | FunctionCallExpression
                        | StructExpression
                        | ArrayExpression
                        | BitCastExpression
                        ;
PlaceExpression         = PathExpression
                        | ArrayIndexExpression
                        | FieldAccessExpression
                        ;

An expression is an element of the program which can be evaluated to produce a value.

An expression can have effects (“side effects”) during evaluation.

The meaning of each kind of expression dictates:

  • whether the expression contains sub-expressions (operands)
  • under what circumstances operands are evaluated (including re-evaluation)
  • how the values produced by operands combine to obtain the expressions value

Expressions with blocks

Block expressions, loop expressions and if expressions whose last branch is a block are expressions with blocks. They can only be used as a whole expression, where nothing follows them:

They cannot be used as an operand of any other operator, or as an array item, a struct field value, an array index or an if condition. To use one there, wrap it in parentheses:

global G: u8;

fn main() {
    let a: u8 = ({ yield G; }) + 1; // ok
    let b: u8 = a - ({ yield 3; }); // ok
}
fn main() {
    let a: u8 = { yield 1; } + 1; // error: cannot be used as an operand
    let b: u8 = a - { yield 3; }; // error: cannot be used as an operand
}

Similarly, an assignment whose right-hand side is an expression with a block cannot be followed by another operator: x = { yield 1; } + 1 is an error, and must be written as x = ({ yield 1; }) + 1.

Expression precedence

The order in which expressions are evaluated is governed by a set of conventions.

  • expression types can be grouped and ranked into levels
  • this rank is called the expression precedence
  • levels are ranked from strongest (highest) to weakest (lowest) precedence, where stronger precedence expressions are evaluated before weaker precedence
  • binary operator expressions within the same level are further ordered by the associativity, either from left to right, from right to left, or neither in which case they require parentheses
  • expression precedence can be overridden using parentheses forming a grouped expression
Expression typeAssociativity
GroupedN/A
PathsN/A
Field accessleft to right
Function calls, Array indexN/A
Unary -, !N/A
asleft to right
Binary -, +left to right
<<, >>, <%, >%N/A
&left to right
^left to right
|left to right
==, !=, <, >, <=, >=requires parentheses
&&left to right
||left to right
=, +=, -=, &=, |=, ^=right to left

Place expressions

Place expressions are expressions which represent a location in memory or on a register which can be referenced.

They include:

Literal expressions

LiteralExpression   = NumberLiteral
                    ;

Struct expressions

StructExpression    = Identifier , "{" , [ StructExprFields ] , "}"
                    ;
StructExprFields    =   StructExprField , { "," , StructExprField } , [ "," ]
                    ;
StructExprField     =   Identifier, ":", ExpressionWithoutBlock
                    ;

Array expressions

ArrayExpression     = "[" , ArrayExprItems , "]"
                    ;
ArrayExprItems      = ExpressionWithoutBlock , { ",",  ExpressionWithoutBlock } , [ "," ]
                    | ExpressionWithoutBlock , ";" , NumberLiteral
                    ;

Bulk fill

Assigning a repeat expression ([value; N]) directly to a global variable whose array type is larger than 16 bits lowers to a runtime fill loop instead of materializing the array in a local:

global OAM: [u8; 160];

fn main() {
    OAM = [0; 160]; // runtime fill loop
}

This is restricted to:

  • array item types u8/i8 (other item types are not yet supported)
  • a value that is a compile-time-constant literal integer (optionally negated for i8) - a runtime-computed value, or a reference to a const item, is not yet supported

See bulk copy in operator expressions for copying an oversized array/struct from another global or const.

Path expressions

PathExpression  =   Identifier
                ;

Operator expressions

OperatorExpression      =   NotExpression
                        |   NegateExpression
                        |   LogicalExpression
                        |   ArithmeticExpression
                        |   ComparisonExpression
                        |   ShiftExpression
                        |   RotateExpression
                        |   AssignExpression
                        ;
NotExpression           =   "!" , ExpressionWithoutBlock
                        ;
NegateExpression        =   "-" , ExpressionWithoutBlock
                        ;
LogicalExpression       =   ExpressionWithoutBlock , "&&" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "||" , ExpressionWithoutBlock
                        ;
ArithmeticExpression    =   ExpressionWithoutBlock , "&" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "|" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "^" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "+" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "-" , ExpressionWithoutBlock
                        ;
ComparisonExpression    =   ExpressionWithoutBlock , "==" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "!=" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "<" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , "<=" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , ">=" , ExpressionWithoutBlock
                        |   ExpressionWithoutBlock , ">" , ExpressionWithoutBlock
                        ;
ShiftExpression         =   ExpressionWithoutBlock , "<<"
                        |   ExpressionWithoutBlock , ">>"
                        ;
RotateExpression        =   ExpressionWithoutBlock , "<%"
                        |   ExpressionWithoutBlock , ">%"
                        ;
AssignExpression        =   PlaceExpression , "=" , Expression
                        |   PlaceExpression , "+=" , Expression
                        |   PlaceExpression , "-=" , Expression
                        |   PlaceExpression , "&=" , Expression
                        |   PlaceExpression , "|=" , Expression
                        |   PlaceExpression , "^=" , Expression
                        ;

Not operator

  • ! is logical NOT for booleans and bitwise NOT for integers
  • results in same type as input

Negate operator

  • - negates
  • results in integer

Logical operators

  • Operands must be booleans
  • && evaluates right operand if left is true
  • || evaluates right operand if left is false
  • Results in boolean

Arithmetic operators

  • & is bitwise AND
  • | is bitwise OR
  • ^ is bitwise XOR
  • + adds
  • - subs
  • Results in integer

Comparison operators

  • == equal
  • != not equal
  • < less than
  • <= less than or equal
  • >= greater than or equal
  • > greater than
  • operands are integers
  • results in a boolean

Shift operators

  • << shift left
  • >> shift right (logical shift right if unsigned, arithmetic shift right if signed)

Rotate operators

  • <% rotate left
  • >% rotate right

Assign operators

  • Operates the same as respective operator but assigns result left operand
  • left operand must be a place expression
  • right operand can be an expression with a block, such as x = { yield 1; }, but then no other operator can follow it

Bulk copy

Assigning a whole array or struct value (dst = src;) is supported when both operands fit in a register (16 bits or fewer) using the same load/store mechanism as scalar assignment.

For types larger than 16 bits, direct global-to-global or const-to-global are permitted.

global A: [u8; 20];
global B: [u8; 20];

fn main() {
    A = B; // runtime copy loop
}

Literal array expressions as described in array expressions are also permitted.

Grouped expressions

GroupedExpression   =   "(" , Expression , ")"
                    ;

A grouped expression can contain an expression with a block, which allows it to be used as an operand:

global G: u8;

fn main() {
    let x: u8 = ({
        yield G;
    }) + 1;
}

Block expressions

BlockExpression     =   "{" , { Statement } , "}"
                    ;

Block expressions are a series of statements which result in a value.

Unlike other languages, the tail expression of a block does not impact the result of the expression. Instead, yield and break statements impact the type. If the block contains no such statements, the result is unit.

fn main() {
    let x: u8 = {
        yield 1;
    };
}

A block expression is an expression with a block, so it cannot be used directly as an operand. Wrap it in a grouped expression instead:

global G: u8;

fn main() {
    let x: u8 = 0;
    x = {
        yield G;
    };
    x += ({
        yield 1;
    }) + 1;
}
  • yield cannot be used in the top level block of a function (its body)
  • yield cannot be used in a loop block. Use break instead

Loop expressions

LoopExpression      =     "loop" , BlockExpression
                    ;

const-loop preview feature

Warning

Requires const-loop preview feature enabled.

Using a loop expression inside a const item’s initializer requires the const-loop preview feature to be enabled:

const SUM: u8 = {
    let i = 0;
    let sum = 0;
    loop {
        if i == 5 then {
            break;
        }
        sum = sum + i;
        i = i + 1;
    }
    yield sum; // requires `const-loop`
};

If expressions

IfExpressionWithoutBlock    =   "if" , ExpressionWithoutBlock , "then" , ExpressionWithoutBlock
                            |   "if" , ExpressionWithoutBlock , "then" , Expression , "else" , ExpressionWithoutBlock
                            ;
IfExpressionWithBlock       =   "if" , ExpressionWithoutBlock , "then" , ExpressionWithBlock
                            |   "if" , ExpressionWithoutBlock , "then" , Expression , "else" , ExpressionWithBlock
                            ;

Each branch can independently be an expression with a block or without one. The last branch determines which kind the whole if expression is: it is an expression with a block when its last branch is one.

global G: u8;

fn main() {
    let c = G;
    let x: u8 = if c == 1 then {
        yield 1;
    } else 2;
    if c == 2 then G = x else {
        G = 0;
    }
}

Field access expressions

FieldAccessExpression   =   ExpressionWithoutBlock  , "." , Identifier
                        ;

A field access expression evaluates the operand and produces the value of the named field.

local-field-access preview feature

Warning

Requires local-field-access preview feature enabled.

Accessing a field of a local variable at runtime requires the local-field-access preview feature to be enabled:

struct Point { x: u8, y: u8 }
global P: Point;

fn main() {
    let p = P;
    let x: u8 = p.x; // requires `local-field-access`
}

The preview feature is not required when the field access operand is a global variable or when it appears inside a const item, as those forms are evaluated without needing to materialise the aggregate in a local:

struct Point { x: u8, y: u8 }
global P: Point;

const ORIGIN_X: u8 = {
    let p: Point = Point { x: 0, y: 0 };
    yield p.x; // ok, evaluated at compile time
};

fn main() {
    let x: u8 = P.x; // ok, field access on a global
}

Function call expressions

FunctionCallExpression  =   PlaceExpression , "(" , ")"
                        ;

Array index expressions

ArrayIndexExpression    =   ExpressionWithoutBlock , "[" , ExpressionWithoutBlock , "]"
                        ;

An array index expression evaluates the operand and the index expression and produces the element of the array at that index. The index expression must be a u16.

local-array preview feature

Warning

Requires local-array preview feature enabled.

Indexing a local variable at runtime requires the local-array preview feature to be enabled:

global A: [u8; 2];

fn main() {
    let a = A;
    let first: u8 = a[0]; // requires `local-array`
}

The preview feature is not required when the indexed operand is a global variable or when it appears inside a const item:

global A: [u8; 2];

const SECOND: u8 = {
    let a: [u8; 2] = [1, 2];
    yield a[1]; // ok, evaluated at compile time
};

fn main() {
    let first: u8 = A[0]; // ok, index on a global
}

Bit cast expressions

BitCastExpression   =   ExpressionWithoutBlock  , "as" , TypeUse
                    ;

A bit cast expression transmutes the value on the left hand side to the type on the right hand side, producing a value that is bit-identical.

Which types a value can be bit cast to are governed by the following rules:

  • Both the source and destination types must have the same bit size
  • The destination type must have a bit size greater than 0
  • If the source and destination types are different, the both must have no padding including explicit padding
  • The type an integer literal on the left hand side will be inferred as the type of the right hand side

A value can always be bit cast to the type it is already.

Below are all examples of valid bit casts:

struct BytePair {
    low: u8,
    high: u8,
}

fn main() {
    let a: u16 = 512;
    let b = a as u16;
    let c = b as i16;
    let d = c as BytePair;
    let e = d as [u8; 2];
}

Statements

Statement   =   LetStatement
            |   ReturnStatement
            |   YieldStatement
            |   BreakStatement
            |   ContinueStatement
            |   BreakpointStatement
            |   ExpressionStatement
            ;

Let statements

LetStatement    =   "let" , Identifier , [ ":" , TypeUse ] , "=" , Expression , ";"
                ;

Restrictions

Quokka has a size restriction on what types can be stored in local variables due to the target hardware’s limitations. When declared within functions, the type of a let declaration must be less than or equal to 16 bits. This limitation does apply to const declarations which are evaluated at compile time and as a result can be larger.

Return statements

ReturnStatement =   "return" , [ Expression ] , ";"
                ;

Restrictions

The same restrictions on size apply to return types as they do for let declarations.

Yield statements

YieldStatement  =   "yield" , Expression , ";"
                ;

Break statements

BreakStatement  =   "break" , [ Expression ] , ";"
                ;

Continue statements

ContinueStatement   =   "continue" , ";"
                    ;

Breakpoint statements

BreakpointStatement =   "breakpoint" , ";"
                    ;

Warning

Requires breakpoint preview feature enabled.

A breakpoint statement compiles to a single LD B, B instruction at that point in the program. Loading B into itself has no effect, so a program behaves identically with or without breakpoints, including on real hardware. Many Game Boy emulators can be configured to pause execution when LD B, B executes, making it a software breakpoint for debugging.

global COUNT: u8;

fn main() {
    COUNT = 1;
    breakpoint;
    COUNT += 1;
}

Breakpoints are never removed or reordered by optimization, and no other code generated by the compiler uses LD B, B.

Observable state

When execution pauses at a breakpoint, any value that is still used later in the program and is present in a register or memory holds the value the unoptimized program would have computed at that point. Optimization may leave a value absent instead. For example, a value may be folded into a constant or its computation may be combined with a later one, but a value is never replaced by a different intermediate result while it can be observed at a breakpoint.

global N: u8;
global RESULT: u8;

fn main() {
    let n = N;
    let m = n ^ 3;
    let a = n + 5;
    breakpoint; // `a` holds `n + 5` here
    RESULT = a + m;
}

Without the breakpoint, the compiler is free to compute a + m as (n + m) + 5, so no register would ever hold n + 5. The breakpoint prevents rewrites like this only where the affected value is observable, so the rest of the program is optimized as usual. Values that are no longer used after a breakpoint have no such guarantee.

A breakpoint statement is not allowed inside a constant declaration, as constant declarations are evaluated at compile time.

Expression statements

ExpressionStatement =   ExpressionWithoutBlock , ";"
                    |   ExpressionWithBlock
                    ;

Attributes

Attribute       =   "#" , "[" , Identifier , [ "=" , AttributeValue ] , "]"
AttributeValue  =   Identifier
                |   NumberLiteral
                ;
#[region = rom0]
#[address = 0x0150]
fn checkpoint() {
}

Types

TypeUse         =   SimpleTypeUse
                |   ArrayTypeUse
                ;
SimpleTypeUse   =   Identifier
                ;
ArrayTypeUse    =   "[" , TypeUse , ";" , NumberLiteral , "]"
                ;

Types define the shape of values within a program.

Every expression, local and global variable, constant has an associated type.

There are four main categories of types:

  • Primitive types
  • User-defined structure types (struct types)
  • Array types
  • Function pointer types

Primitive types

  • Numbers
    • u1
    • u2 (requires narrow-int preview feature enabled)
    • u4 (requires narrow-int preview feature enabled)
    • u8
    • u16
    • i8
    • i16
  • never
  • unit

Array types

i.e. [ItemType; Count]

User-defined structure types (struct types)

See Structs

Function pointer types

See Functions