Cheat Sheet
Need a quick reminder of how to write something? These small, complete programs demonstrate common Adder tasks. Each section links to the handbook chapter with the full contract.
Declarations
const declares a fixed value, var declares mutable state, and <- creates a reactive binding or hardware output that stays in sync automatically. Inside a handler or its loops, name = expression updates existing var state. See Types and Declarations.
type Lane = Number<0...39> // a friendly nickname for a type
enum Mode
case title, playing, over
end
struct Speed(x: Number<-3...3>, y: Number<-3...3> = 0)
const limit = 40 // a constant: fixed before the program runs
var lane: Lane = 0 // state: remembered from frame to frame
var mode: Mode = .title
var speed: Speed = (x: 1)
fn mirror(x: Lane): Lane // a pure function: same inputs, same answer
Lane.last - x
end
op change(value: Lane) // an op: a calculation that remembers past frames
value - value.previous(from: value)
end
far <- mirror(lane) // a binding: updates whenever lane changes
moved <- change(lane) != 0
System.screen.border <- if moved then .yellow else .black end
System.screen.text[0][0..<2] <- far.digits(2)
when System.keyboard.space.pressed // a handler: runs when an event happens
lane = lane +% 1
mode = mode.next()
endA struct block can bundle fields and helper functions together (mut fn can update the struct's own var fields), and at places a value at a specific memory address.
struct Score
step: Number<u8>
var points: Number<0...999> = 0
mut fn award()
points = points +| step
end
fn text(): [3 of Char]
points.digits(3)
end
end
var score = Score(step: 10)
seen: Number<u8> at 0xC000
when System.keyboard.space.pressed
score.award()
end
System.screen.text[0][0..<3] <- score.text()
System.screen.border <- Color(seen % 16)To split a larger project across files, include "lib/world" brings another file from the project into your program.
Loading and saving data
load gives nil while it reads, then a value or a reason. Adder reports .damaged for damaged contents and .wrong_type for a different saved type. The drive's own errors use .device_error(code:); every reason has a message padded to 40 characters. See Results and Failures and Disk Drives.
loaded: Result of Number<u8>? <- System.drive[8].load("score")
System.screen.border <- match loaded
nil -> .light_blue
success(value) -> .green
failure(reason) -> match reason
damaged -> .yellow
wrong_type -> .purple
else -> .red
end
endA save binding writes its value each time it changes, never at start, and holds what the drive answered:
var record: Number<u16> = 0
saved: Result of Receipt? <- System.drive[8].save("best", record)Numbers
Every number in Adder knows the range of values it can hold. Write a custom range like Number<0...9> or Number<0..<40>, or pick a hardware storage format directly (u8, i8, u16, i16 for whole numbers, and u8.8, i8.8, u16.8, i16.8 for fractions in steps of 1/256). Writing Number by itself gives you a two-byte whole number from -32,768 to 32,767. See Numbers and Expressions.
var a: Number<u8> = 0xFF // also 255 or 0b1111_1111
var b: Number<0...9> = 5
var c: Number<0..<40> = 0
var d: Number<-2.0...2.0> = 0.5
const mask = 0b0000_0101
when System.screen.frame
b = b +% 1 // wraps around: 9 steps back to 0
c = c +| 3 // clamps at the top: stops at 39
a = a.bitwise_and(mask).shift_left(1)
end
whole <- d.floor() // also round() and ceil()
byte <- Number<u8>(b) // an explicit conversion
System.screen.border <- Color(b)When a calculation reaches the edge of a variable's range, the operator you choose decides what happens next:
| Operator | What happens if the result leaves the range |
|---|---|
+ - * | stops the program and reports the line number on screen |
+% -% | wraps around to the other end of the range |
+| -| | clamps at the nearer end of the range |
/ % | dividing by zero stops the program and names the line |
Whole-number a * b / c keeps an exact private product and checks the quotient against its destination; its three inputs must fit signed 16 bits. A product on its own is checked: (a * b) % 16 takes the remainder only after multiplication succeeds.
Control
Use if ... then ... end for conditions and match for branching on cases or condition tables. Inside a when handler, you can filter events with a second when, bail out early with guard, or pause across frames with wait. See Events and Handlers and Statements.
var lives: Number<0...3> = 3
var score: Number<0...99> = 0
shade <- if lives == 1 then Color.red else Color.black end
System.screen.border <- match
when lives == 0 -> Color.gray
else -> shade
end
when System.keyboard.space.pressed when lives > 0
lives = lives - 1
end
when lives.changed
guard lives == 0 // stops the handler here unless true
score = 0
end
when start
forever // repeats; every turn must reach a wait
wait(ms: 500) // or wait(30) frames, wait(seconds: 2)
score = score +% 1
end
endAmong declarations, a match or an if holds declarations, and what a case declares exists only while the case matches. Blocks side by side run independently; their active cases must bind different parts. A case can bind an output or placed destination declared above it, and its queues and jobs restart with it. A match divides the program into cases—such as a title screen and a play screen—where only the active case's bindings and handlers run. Cases can add when condition; without a value after match, ordered when condition -> lines and a final else -> choose the case.
enum Scene
case title, game
end
var scene: Scene = .title
match scene
title ->
System.screen.text[11][15..<25] <- "PRESS FIRE"
when System.joystick[2].fire.pressed
scene = .game
end
game ->
System.screen.border <- .green
when start
wait(seconds: 2)
wait System.joystick[2].fire.pressed
scene = .title
end
endLists and Slices
[n of T] is a fixed-length list of n items. Put a range in brackets to take a window (slice) into a list, or two ranges to take a 2D rectangle from a grid of rows. See Lists and Expressions.
var xs: [8 of Number<u8>] = [3, 1, 4, 1, 5, 9, 2, 6]
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
var left: Number<0...4> = 0
window <- xs[left..<(left + 4)] // a 4-item window whose start can slide
corner <- grid[0..<2, 1..<3] // a 2-by-2 rectangle
big <- xs |> filter(fn(n) -> n > 3) // keeps matching items as Number<u8>?
doubled <- xs |> map(fn(n) -> n * 2)
all_of <- sum(xs)
fn add_up(values: [n of Number<u8>]): Number<u16>
var t: Number<u16> = 0
for v in values
t = t + v
end
t
end
part <- add_up(window)
when System.keyboard.space.pressed
xs[0] = 7
left = (left + 1) % 5
endOptionals
Add ? to any type (T?) when a place might either hold a value or be empty (nil). See Optionals.
var held: Number<u8>? = nil
when System.keyboard.space.pressed
held = 7
end
when System.keyboard.delete.pressed
if n = held then // unwraps and names the value when present
held = n -| 1
end
end
shown <- held ?? 0 // uses 0 when held is nil
System.screen.border <- if held != nil then Color(shown % 16) else .black endDevices
Every part of the Commodore 64 lives under System—no hex addresses required. See The System Device Tree.
| Device | Members |
|---|---|
System.screen | border, background, text, content, color, font, sprite, frame, frames, standard, frame_cycles, canvas(...), region(...) |
| a region | text, print, println, newline, home, clear, shown, cursor |
| a canvas | drawings, color, background, shown |
System.screen.sprite[i] | x, y, shown, shape, color |
System.keyboard | each key by name, stroke, line, caret, dropped |
System.joystick[1], [2] | dx, dy, fire |
System.mouse | x, y, left, right |
System.paddle[1], [2] | a knob reading from 0 to 255 |
System.sound[1].voice[1] to [3] | <- a held Tone or .silence, play(...), release |
System.clock | interval(...), timer(...), hours, minutes, seconds, tenths |
For an editable prompt, set the line's capacity and show the line with a cursor. Keep one more visible cell than the capacity if the cursor should remain visible at the end of a full line:
System.keyboard.line.capacity <- 15
System.screen.content <- Text(System.keyboard.line).at(row: 2, col: 2).width(16).cursor(.flashing).cursor(.steady) stays shown and .cursor(.hidden) shows none; omitting .cursor draws none either. A cursor needs a fixed screen position, a machine font and character wrapping. Typing overwrites; INST inserts a space, DEL deletes to the left, HOME goes to zero, CLR clears and RETURN submits. The two Commodore cursor keys mean right/down, or left/up with either Shift. Up/down follow the rows of a wrapped cursor box. See Typed line and cursor for the bounds and browser keys.
bat: Number<0...296> <- (System.joystick[2].dx * 4).sum(from: 136)
held <- System.joystick[2].fire
beat <- System.clock.interval(seconds: 0.25)
var hue: Number<0...15> = 0
when beat
hue = hue +% 1
end
when System.keyboard.space.pressed
System.sound[1].voice[2].play(Tone(.c6, decay: .short))
end
System.screen.border <- Color(hue)
System.screen.background <- .black
System.screen.text[0][0..<5] <- "SCORE"
System.screen.color[0][0..<5] <- .yellow
System.screen.sprite[0] <- (x: bat, y: 170, color: .white)
System.sound[1].voice[1] <- if held then Tone(.c4) else .silence endconst picture = System.screen.canvas()
const badge = Picture(["XXXXXXXX", "X......X", "X......X", "XXXXXXXX"])
x: Number<0...312> <- System.joystick[2].dx.sum(from: 80)
picture.color <- .yellow
picture.background <- .blue
picture.drawings <- [badge.place(x: x, y: 40), Text("SCORE").place(x: 16, y: 8)]const log = System.screen.region(row: 1, height: 3, width: 12)
var items: Number<0...999> = 0
when System.screen.frame.every(30)
items = items +% 1
log.println(items.digits(3))
endInterrupt Routines
When you want local calculations, immediate scalar register stores or 6510 assembly to run at a specific raster line on screen or on a millisecond timer, wrap it in an interrupt handler. The compiler wires up the interrupt and budgets its cycles in every frame. See Interrupt Routines.
when System.screen.interrupt(line: 49) // once a frame, when the beam hits line 100
var shade: Number<u8> = 2
shade = shade +% 1
System.screen.border = Color(shade)
end
when System.clock.interrupt(ms: 20) // every 20 milliseconds
asm
inc ticks
ticks:
.byte 0
end
endCosts
By default, the compiler proves that each logical update fits one display refresh on every supported video standard. The explicit #allow frame_skips directive permits some finite foreground calculations to span refreshes while keeping timing-sensitive work checked. When a heavy loop needs a speed boost, put fast before a handler, function, op, binding, or case to spend extra bytes for faster code. See Costs and the Frame.
var weights: [64 of Number<u8>] = 3
var levels: [64 of Number<u8>] = 5
var mix: Number<u16> = 0
fast when System.screen.frame
var acc: Number<u16> = 0
for i in 0..<64
acc = acc +% weights[i] * levels[i]
end
mix = acc
end
System.screen.border <- Color(mix % 16)fast forces the listed larger, faster forms on a code head; small keeps its compact forms. Both can mark functions, ops, handlers, bindings, case patterns and regions. The innermost mark decides, including an explicitly marked body copied at a call.
Command-line Compiler
Download the standalone adder executable for macOS, Linux or Windows from GitHub Releases, extract it and put it on your PATH. It needs no Node.js or Bun runtime.
| Command | Purpose |
|---|---|
adder new my-game | Create a project and choose a starter. |
adder compile my-game -o out/my-game.prg | Compile the project into a C64 program. |
adder costs my-game --listing | Show static byte counts, cycle estimates, PAL/NTSC frame bounds and generated assembly. |
adder format my-game | Format the project's sources in place; add --check to check without writing. |
adder lsp --stdio | Start the language server for an editor or other LSP client. |
adder --help | List commands. Use adder help compile for one command's options. |
Compilation writes out/my-game.prg and the sibling out/my-game.lbl VICE symbol map. Open the .prg in a C64 emulator such as VICE, or transfer it to your C64. To compile a source file directly, use adder compile my-game/src/main.adder -o out/my-game.prg. A scaffolded project's project.json chooses its main source file; the compiler loads its included sources and assets.
See Costs and the Frame to read the cost report.
Fetch rows from RAM expansion
Use a slice to choose destination rows and stride to space their source rows. Omit stride when the source rows lie back to back. Use wrap: 1..<29 for a repeating source range. The call checks every row before copying. See RAM Expansion Units.
var back: [25 of [40 of Number<u8>]] = 0
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut back[13..<25], bank: 0, offset: 6656, stride: 512)
end
end
endAbout the Language Reference
Think of this reference as your desk manual for Adder and the Commodore 64. Each chapter takes one part of the language and shows you how to write it, what it means at runtime, which types and number ranges it works with, what it costs in bytes and processor cycles, and how the compiler helps you catch mistakes early.
If you would rather learn by building a small arcade game from scratch, begin with the Adder Quickstart and come back here whenever you are curious about the full details of a feature.
Visit the Changelog for the complete history of new features, fixes and improvements in Adder and the Lab.
Examples
Runnable Adder examples are complete programs you can paste into the Lab or save to a .adder file. Blocks marked as fragments show part of a program, an external file or a command; use them in the surrounding context described by the chapter.
For example, this complete program changes the border:
System.screen.border <- Color.light_blueWhenever a chapter explains a rule that the compiler checks before your program runs, it names the message key in backticks, such as wrongType. You can look up any key in Diagnostics to see the exact message the compiler gives and how to fix it.
Lexical Structure
Before your program can light up the screen or play a note, the compiler reads your source text character by character and groups those characters into tokens: names, reserved words, literals, operators and punctuation. It scans each line from left to right and always takes the longest run of characters that forms a valid token at each spot—so format is read as one whole name rather than the reserved word for followed by mat, and <= is one operator rather than < followed by =.
Source Text
An Adder source file is Unicode text saved as UTF-8, so you can write names and comments in your own language. A byte-order mark at the very start of a file is ignored. If a file contains bytes that are not valid UTF-8, the compiler stops at the first one and tells you its line and column.
Outside comments and text in quotes, every character you type belongs either to a token or to the whitespace between tokens. If a stray character slips in, the compiler points it out once, with its code point (such as U+00A0), and keeps reading, so one slip never hides the rest of your program. Columns in messages count characters, not bytes.
Only the space, the tab, the carriage return and the line feed separate tokens. Other kinds of space, such as the no-break space, are refused, because they look like a space but are not one. They carry no hidden meaning. Indentation is purely for your own eyes: every block closes explicitly with the word end, never with a shift in indentation, so you can lay out your code however it reads best to you.
Comments
A comment starts with // and runs to the end of the line. The compiler skips right past it, so you can jot down any characters or notes you like inside, in any language, with emoji if you like. The one exception is the set of hidden text-direction controls (U+202A to U+202E and U+2066 to U+2069): they can make a line read differently from how it compiles, so they are refused everywhere in a file, including comments and text in quotes. Adder has no multi-line comment marker; for a longer note, just start each line with //.
// The border steps through its sixteen colors.
var hue: Number<0...15> = 0 // the color shown now
when System.screen.frame
hue = hue +% 1
end
System.screen.border <- Color(hue)Lines
A line break finishes a declaration or a statement, giving each line a single job. Adder uses no semicolons and keeps one declaration to a line; if you pack two declarations onto one line or end a line with a semicolon, the compiler catches it right away.
When a call, a struct value or a list grows long, you can split it across lines inside an open ( or [ at four clean spots:
- right after the opening bracket;
- right after a comma;
- right after the
->of a function value, so its body can start on the next line; - right after a finished item, just before the closing bracket.
You are welcome to leave a trailing comma on the last item of a call, a struct value or a list—handy when you rearrange lines later. A value if or match inside brackets keeps its own multi-line layout.
System.screen.content <- Text("Hello").at(
row: 2,
col: 4,
)If a line breaks anywhere else inside brackets—such as right after a colon or an operator—the compiler flags the break and names the bracket that is still waiting to close.
Brackets can nest up to 16 levels deep within a single expression. If an expression burrows deeper than that, the compiler stops with nestingExpression and invites you to pull part of the calculation out onto an earlier line with its own name.
Source Directives
#assert condition, "explanation" checks a fixed relationship during compilation. #allow frame_skips lets the main source file request bounded slower updates. Each directive occupies one physical line, begins at its first non-whitespace character, and may have a trailing // comment. The # touches the directive word: # assert and call-style #assert(...) are refused. Names such as assert, allow and frame_skips remain available for ordinary declarations.
Comments, quoted strings and art rows do not activate directives. Inside assembly, # retains its immediate-operand meaning, including lda #assert when assert names a constant. These directives do not define macros or introduce conditional compilation. See Compile-Time Assertions for the permitted conditions and placement.
Names
A name starts with a letter from any language or with an underscore, followed by any mix of letters, combining marks, digits and underscores. The Unicode standard decides what counts as a letter, so größe, 距離 and ταχύτητα are all fine names, while an emoji or a symbol such as × is not. Reserved words, built-in names, operators and the digits of a number stay plain ASCII. Case matters: score and Score are two distinct names.
Two spellings of the same letter are the same name. é typed as one character and é typed as e plus a combining accent refer to the same variable.
Two different names that look alike are refused when at least one of them uses letters outside ASCII: a Latin cop and a Cyrillic сор would be easy to mix up, so the compiler asks you to rename one (lookalikeNames). Two ASCII names such as x1 and xl are not checked. In the finished program, a letter outside ASCII is spelled as _u followed by its hexadecimal number, so the .lbl label file stays plain ASCII; if two names would collide that way, the compiler refuses the program (symbolCollision). Messages, the Lab and your editor keep showing your names as you wrote them.
You can tell a type from a value at a glance by its very first character:
- a type name—for a
type,enumorstruct—starts with an uppercase letter, in any script (Ölfass,Δρόμος); - a value name—for a constant, variable, binding, function, op or parameter—starts with any other letter or an underscore, including a letter from a script without capitals, so
距離is a value name.
A generic type parameter is a single uppercase letter. A type needs an uppercase initial from a script that has capitals.
If those get swapped, the compiler gently steers you back: a capitalized value declaration triggers capitalizedDeclaration, and a lowercase type declaration triggers aliasName, enumName or structName.
Reserved words (listed under Reserved Words) cannot be used as names, and any name starting with two underscores (__) is reserved for the compiler's own machinery (internalName). A handful of built-in names mean the exact same thing in every program, so the compiler keeps them safe from redeclaration with builtinName: the built-in types, the root word System that starts every device path, and the scratch workspace used in assembly. Collection function names such as count, sum, min and map are ordinary names. An authored declaration or binding takes precedence over the standard function from that point onward; a mismatching authored call reports its own error. Type-specific member names such as digits and random are also available as value names without changing calls such as score.digits(3).
Reserved Words
These keywords form the backbone of the language and are never used as ordinary names. Number opens every numeric type, and the eight storage format names appear only inside Number<...>, though none of them may name a value.
| Kind | Words |
|---|---|
| Keywords | action, and, as, asm, at, break, case, const, else, end, enum, export, false, fast, fn, for, forever, guard, if, in, include, import, match, mut, nil, not, Number, of, on, op, or, output, partial, protocol, publish, small, start, String, struct, then, true, type, var, wait, when, wire, work |
| Format names | u8, i8, u16, i16, u8.8, i8.8, u16.8, i16.8 |
Right after a ., at and publish are member names rather than keywords, as in Text("SCORE").at(row: 0, col: 2).
Words Inside Assembly
Step inside an asm block and the vocabulary shifts to match the processor. Inside asm, the 6510 instruction mnemonics below become reserved words, while guard, start, then, for, break, wait and forever relax into ordinary names. Outside asm, those instruction mnemonics are free for your own variables—so calling a counter inc or dex in regular Adder code is completely fine. The header words writes, runs and cycles are reserved only on the opening line of an asm block, where they introduce its optional clauses, and the addressing marks below belong exclusively to assembly lines. Inside assembly, hexadecimal numbers wear a leading $ and binary numbers wear a leading %. Turn to the Assembly chapter for the full tour.
| Kind | Tokens |
|---|---|
| Clauses and directives | writes, runs, cycles, #, ,x, ,y, .lo, .hi, .byte, .text |
| 6510 instructions | adc, alr, anc, and, arr, asl, asr, axs, bcc, bcs, beq, bit, bmi, bne, bpl, brk, bvc, bvs, clc, cld, cli, clv, cmp, cpx, cpy, dcp, dec, dex, dey, eor, inc, inx, iny, isb, isc, jmp, jsr, lax, lda, ldx, ldy, lsr, nop, ora, pha, php, pla, plp, rla, rol, ror, rra, rti, rts, sax, sbc, sbx, sec, sed, sei, slo, sre, sta, stx, sty, tax, tay, tsx, txa, txs, tya |
Literals
A literal spells out a fixed value right in your code: a number, a quoted string of text, a yes-or-no flag or nil.
Whole-Number Literals
You can write a whole number in everyday decimal digits, in hexadecimal after 0x, or in binary after 0b—perfect when you are masking bits or laying out hardware flags. Both the prefix letters (0x, 0X, 0b, 0B) and the hexadecimal digits (a–f or A–F) accept uppercase or lowercase. In hexadecimal and binary literals, you can tuck a single underscore between digits to group nybbles or bytes cleanly (0b0000_0101). Decimal literals are written as plain digits without underscores.
How you write the literal never locks in its storage width or type. 5, 0x05 and 0b0000_0101 are the exact same number five; the spot that receives the number decides how it is stored, as Types explains.
const north_and_south: Number<u8> = 0b0000_0101
var open_paths: Number<u8> = 0x0F
either_open <- open_paths.bitwise_and(north_and_south) != 0
System.screen.border <- if either_open then .green else .red endA number literal itself is always positive: -5 is the unary - operator applied to 5. If a number is mistyped—say, trailing letters after digits, a 0x or 0b prefix with no digits, a leading or trailing underscore, or two underscores side by side—the compiler flags it with badNumber.
Decimal Literals
A decimal literal has digits on both sides of a decimal point, like 0.5 or 3.25. It holds its exact mathematical value until it lands in a destination type, which then snaps it to the nearest fixed-point step of 1/256. Writing a decimal point always marks the literal as fractional, even when the fraction part is zero—so 2.0 asks for a fractional type while 2 stays a whole number.
Handing a decimal literal to a whole-number type won't slip past the compiler; use a whole number or an explicit rounding call instead.
String Literals
A string literal is a row of ASCII letters, digits, spaces and supported punctuation, wrapped in double quotes on a single line. Ordinary String literals refuse backtick (`), braces ({ and }) and tilde (~): the C64's lowercase/uppercase character set has no glyph for them. Direct ScreenCode("...") literals accept them for custom-font tiles, keeping their existing conversion values. Inside the quotes, \" produces a literal double quote and \\ produces a literal backslash; \(expression) inserts a String, Char, fixed Char list or Number value. Quote and backslash escapes keep their meaning inside each nested string.
A string literal is a bounded value with live content: "HELLO" has the type String<5>. Binding it to a five-cell System.screen.text slice translates its ASCII characters through the active font, as Types shows.
const greeting = "SAY \"HI\""
System.screen.text[0][0..<8] <- greetingThe compiler catches unsupported characters (including accented letters) with stringNotPrintable, naming each character and its code point at its source location. Ordinary String literals are checked even when unused or only compared, because a String can later reach a display through a variable or function. Constants and interpolated text follow the same rule. The four-character exemption applies only to a literal passed directly to ScreenCode (parentheses around the literal are allowed); it does not extend to String variables, compound arguments or interpolation. A string that runs off the end of its line without a closing quote gets unterminatedString, and an unknown backslash escape gets badEscape.
Yes-or-No and Missing Values
true and false are the two values of the boolean type bool. nil stands for the missing value of any optional type.
Operators and Punctuation
These symbol tokens glue expressions and declarations together. The Expressions chapter shows what each operator computes and the precedence order in which they bind.
| Token | Use |
|---|---|
#assert, #allow | compile-time source directives, each on its own physical line |
+, -, *, /, % | arithmetic |
+%, -%, +|, -| | wrapping and clamping addition and subtraction |
==, !=, <, <=, >, >= | comparisons |
..., ..< | a range with its last value, or without it |
?? | fallback value when an optional is nil |
++ | joins two lists or strings |
|>, :> | passes a value as the first argument of the next function |
= | names a constant, gives a variable its first value, or sets a variable in a handler |
<- | keeps a binding or an output equal to an expression |
: | follows a name with its type, and a label with its argument |
-> | follows a pattern in a match, and a parameter in an arrow function |
? | after a type, makes it optional |
(, ), [, ], , | grouping, calls, lists, indexing and separating items |
. | picks a member, or a case of the expected type when it begins a value |
Structural Highlighting
The Lab and VS Code color the angle brackets around type bounds with the type, and color ... and ..< like numbers. In Number<-24...487>, the opening bracket stays distinct from the minus sign. Comparisons, binding arrows, function and match arrows, and both pipe spellings keep the ordinary operator color. Strings, comments and assembly keep their own highlighting.
Interpolation evaluates every hole once, from left to right, and uses the same construction as ++. Number holes use canonical signed decimal formatting; write score.format(decimals: 2) when a fixed precision is needed. An escaped backslash stays literal, so "\\\\(name)" displays \\(name). Holes and their nested strings stay on the same physical line. Include paths, asset filenames and authored art rows require ordinary non-interpolated literals.
var name: String<32> = "Ada"
var score = -7
label <- "Hello \(name), score \(score)"
System.screen.content <- Text(label).at(row: 2, col: 2)action is a reserved declaration, expression and type keyword. do is an ordinary standard function name and may be shadowed by an authored declaration.
Types
Every value in an Adder program has a type, and the compiler knows every type before a single instruction runs. A type tells the machine which values a name can hold and how many precious bytes of memory to set aside for it. Numeric ranges may widen safely, and whole numbers fit fractional places when their ranges fit. Changes of kind, such as a number becoming a color, and dropping a fraction require an explicit conversion or rounding call. If a value of the wrong type is handed to a spot that expects something else, the compiler catches the mismatch right away with wrongType.
Here is the full cast of types you can work with:
- numbers, defined by the exact range of values each one holds;
- yes-or-no values, of type
bool; - named sets built into the machine, such as
Color,NoteandKey; - characters and screen codes for text and screen cells;
- bounded ASCII strings, with a fixed capacity and a changing length;
- pictures and fonts, which the compiler packs straight into your program;
- enums and structs, either declared by your program or built in;
- lists of a fixed length;
- pure function values, which carry a calculation with a checked signature;
- action values, which perform synchronous services without returning a result;
- optionals, which hold either a value or
nil; - events, which happen at specific moments rather than sitting in memory;
- results, which report success or failure from background work;
- game collections and fast primitives, including entity pools, rings, decks, bounds, cooldowns, waves and flags.
Numbers
In Adder, a number type is simply the range of values you need it to hold. Number<low...high> holds every value from low through high, including both ends. Number<low..<high> holds every value from low up to, but stopping just short of, high—handy when counting across 40 columns numbered 0 through 39.
var lives: Number<0...3> = 3
var column: Number<0..<40> = 0
when System.keyboard.space.pressed
lives = lives -| 1
column = column +% 1
end
System.screen.text[0][0..<1] <- lives.digits(1)
System.screen.border <- Color(column % 16)Range Bounds
Both ends of a numeric type's range must be fixed values that the compiler can work out before the program runs. An end can be a literal number, a numeric constant declared earlier, a bound member of a numeric type like Lane.last, a unary minus, or a compile-time calculation built from those using +, -, *, / and %. Whenever an end is a calculation, wrap it in parentheses so the angle brackets stay easy to read. Each bound expression can have at most 128 parts and nest up to 32 levels deep.
const columns = 40
type Column = Number<0..<(columns * 2)>
var column: Column = 0
System.screen.border <- Color(column % 16)A variable, a binding or a live device reading cannot serve as a numeric type's range bound (rangeEndNotFixed). Function calls are also excluded from bound expressions; if a pure call computes a fixed value, put it in an earlier const and use that constant instead. Exclusive for loops have a separate bounded runtime upper-bound form.
Likewise, a range whose starting value is greater than its ending value has no room for any number at all, so the compiler flags it with rangeEmpty.
Fractions
Write a decimal point in either end of a range and you get a fixed-point fractional type, measured in crisp steps of 1/256. Number<0.0...1.0> holds 0, 1/256, 2/256 and so on all the way up to 1—smooth enough for sub-pixel sprite motion and gentle gravity curves without floating-point overhead. In a fractional range, ..< leaves out just the final 1/256 step: Number<0.0..<1.0> tops out at 255/256 (about 0.996).
When a fractional type receives a decimal literal, it snaps the number to the nearest 1/256 step; if that rounding nudges a literal past either end of the range, the compiler lets you know.
A whole number fits naturally into a fractional spot without a conversion whenever its range fits inside. Going the other way—turning a fraction back into a whole number—always asks you to pick how to round it with floor(), round() or ceil(), as Expressions describes.
Saving and loading a fractional number keeps its exact stored 1/256 steps, including inside records and lists. Number<u8.8> uses two bytes and Number<u16.8> uses three; their signed forms keep the same widths.
Storage Formats
The compiler packs each number into the smallest of eight formats that can hold its entire range. If you want the full span of a machine format, you can write the format name itself inside Number<...> instead of a range.
| Format | Holds | Step | Bytes |
|---|---|---|---|
u8 | 0 to 255 | 1 | 1 |
i8 | -128 to 127 | 1 | 1 |
u16 | 0 to 65,535 | 1 | 2 |
i16 | -32,768 to 32,767 | 1 | 2 |
u8.8 | 0 to 255.996 | 1/256 | 2 |
i8.8 | -128 to 127.996 | 1/256 | 2 |
u16.8 | 0 to 65,535.996 | 1/256 | 3 |
i16.8 | -32,768 to 32,767.996 | 1/256 | 3 |
Even when a narrow range rides inside a 1-byte format, it remembers its own exact bounds: Number<0...9> takes one byte in memory and still accepts only 0 through 9. If a range stretches wider than every available format—such as -1 to 65,535, which needs both negative numbers and the top half of a 16-bit unsigned word—the compiler stops with rangeNoRepresentation, and any unknown format name inside Number<...> triggers numericFormat.
Individual bit positions belong to the two unsigned formats: Number<u8> gives you 8 bits and Number<u16> gives you 16, ready for the bit operations in Expressions to inspect and flip. If you have a ranged number or a default Number and want to twiddle its bits, convert it to Number<u8> or Number<u16> first.
The Default Number
Written by itself, Number holds whole numbers from -32,768 to 32,767—the full span of i16. When you declare a var without spelling out its type, it takes that i16 range if its starting value is a whole number, or the i16.8 range if its starting value has a decimal point. Starting a variable at a small number never boxes it in: var score = 0 has plenty of headroom to climb to 30,000 later on.
var score = 0
var speed = 0.5
fn apart(a: Number, b: Number): Number
if a > b then a - b else b - a end
end
System.screen.text[0][0..<3] <- apart(score, 100).digits(3)A <- binding automatically takes the tightest range the compiler can prove for its expression, while a constant keeps its exact single value.
Values Outside a Range
Whenever the compiler can see right away that a value falls outside its target range, it catches the mistake at compile time.
Of course, variables change as the game plays, and the compiler cannot always prove ahead of time that a calculation stays in bounds. When a runtime check is needed, the compiled program guards the store automatically: if an out-of-range number tries to slip in, the program halts cleanly and prints the offending line number right on the screen. When you want a number to loop around or stop at the ends—like a color cycling from 15 back to 0 or a life counter stopping at 0—reach for the wrapping (+%, -%) or clamping (+|, -|) operators described in Expressions.
Type Aliases
type Name = T gives an existing type a clear, domain-specific name of your choosing. An alias is another name for T. Values of either name are interchangeable, and compiler messages use your alias name. For any numeric alias, .first and .last give you its lower and upper bounds by name.
type Lane = Number<0...39>
fn mirror(x: Lane): Lane
Lane.last - x
end
column: Lane <- System.screen.frame.cycle()
System.screen.text[0][0..<2] <- mirror(column).digits(2)Yes-or-No Values
The boolean type bool has just two values—true and false—and takes a single byte. You can combine boolean values with and, or and not. Adder never guesses whether a number or an optional means true or false, so the compiler won't let either one stand in for a bool condition.
var paused: bool = false
when System.keyboard.p.pressed
paused = not paused
end
System.screen.border <- if paused then .red else .black endNamed Sets
The machine's own palettes, musical notes, keys and settings are represented as named sets: each item has both a readable name and an underlying number, and each takes one byte. You can write a value in full, like Color.red, or use the short dotted form .red wherever the expected type is already clear from context. An if or match used to fill System.screen.color also gives its arms this Color context. Inside a match on a named set, each pattern is written as the bare name without a leading dot.
| Type | Numbers | Names |
|---|---|---|
Color | 0 to 15 | black, white, red, cyan, purple, green, blue, yellow, orange, brown, light_red, dark_gray, gray, light_green, light_blue, light_gray |
Pitch | 0 to 11 | c, cs, d, ds, e, f, fs, g, gs, a, as, b |
Note | 0 to 94 | a pitch and an octave, from c0 through c4 (middle C) to as7 |
Key | 0 to 63 | the keys of the keyboard, listed below |
Waveform | 0 to 8 | triangle, sawtooth, square, pulse, noise, triangle_sawtooth, pulse_triangle, pulse_sawtooth, pulse_triangle_sawtooth |
Attack | 0 to 15 | no names |
Decay | 0 to 15 | short (5), medium (8), long (10) |
Sustain | 0 to 15 | no names |
Release | 0 to 15 | no names |
Flip | 0 to 1 | vertical, horizontal |
TextWrap | names only | character, word, hyphenated |
TextAlignment | names only | leading, center, trailing, justified |
CursorStyle | names only | steady, flashing, hidden |
The 64 Key names are delete, return, cursor_right, f7, f1, f3, f5, cursor_down, three, w, a, four, z, s, e, left_shift, five, r, d, six, c, f, t, x, seven, y, g, eight, b, h, u, v, nine, i, j, zero, m, k, o, n, plus, p, l, minus, period, colon, at_sign, comma, pound, asterisk, semicolon, home, right_shift, equals, up_arrow, slash, one, left_arrow, control, two, space, commodore, q and run_stop.
Calling the type's name like a function converts a number into a member of that set: Color(n) picks color number n, and Attack(2) sets a voice attack rate of 2. If a fixed number falls outside the set's valid range, the compiler catches it with conversionOutOfRange; if the number can change while the program runs, the program checks it on the spot.
var hue: Number<0...15> = 0
when System.keyboard.space.pressed
hue = hue +% 1
end
System.screen.border <- Color(hue)
System.screen.background <- Color.random()Narrowed Named Sets
Just like numbers, a named set can be narrowed to a contiguous slice of its values by writing a range in angle brackets after the type name, with both ends included. Note<Note.c3...Note.c5> holds only the two octaves from c3 through c5, and a type alias makes a narrowed set effortless to reuse.
type Melody = Note<Note.c3...Note.c5>
var note: Melody = .c4
when System.keyboard.space.pressed
note = if note == Note.c5 then Note.c3 else Note.c4 end
endCharacters and Screen Codes
A Char represents a single character of text, numbered 0 to 127 in standard ASCII order: Char(65) is A, and Char.space is a blank space. Every string literal is a bounded String<N>. Char("A") produces scalar ASCII 65, just like "A"[0] and Char(65). Char("HELLO") produces [5 of Char]; Char(s) pads a String to its capacity with spaces, like s.padded(width: N). The scalar shorthand applies to one-character literals. For a variable s: String<1>, Char(s) still returns [1 of Char].
A ScreenCode, numbered 0 to 255, is the byte that actually sits in a cell of the text screen to pick one glyph from the active 256-character font. ScreenCode.space is the blank cell and ScreenCode.block is the solid filled block. Calling ScreenCode(text) converts a whole string into the screen codes that display it, while ScreenCode(c) converts a single Char. Ordinary String literals refuse backtick (`), braces ({ and }) and tilde (~) because the C64's lowercase/uppercase font has no glyph for them. Direct ScreenCode("...") literals accept them for custom-font tiles, with the existing font-map conversion values; the exemption does not apply to an ordinary String stored in a variable or built with interpolation. In the C64 font, backslash (\), caret (^) and underscore (_) keep their C64 glyphs: pound sign (£), up arrow (↑) and left arrow (←). In extended background text, ScreenCode(glyph: g, background: bg) packs a glyph index in 0...63 and a background choice in 0...3 into one screen code (bg * 64 + g). ScreenCode("A") is a one-element list without a wider fixed destination. In a fixed [N of ScreenCode] destination, ScreenCode(text) fills fitting text to N cells before conversion, so the characters and spare spaces use the same map. ScreenCode(65) remains a scalar, with the ordinary scalar-fill rule. Raw tile grids and screen buffers use ScreenCode; converting them back to ASCII requires an explicit application mapping. A list of whole numbers from 0 to 255, such as a Number<u8> grid, converts to screen codes without changing a byte, so System.screen.text <- ScreenCode(screens[front]) shows that grid as a list of ScreenCode would be shown: in place when no write reaches the screen on show, and through the screen's copy of it otherwise.
Screen text accepts a String<n> with capacity at most N or [N of Char] directly on an N-cell slice, mapping through the active font and filling spare cells with spaces. A single cell accepts a Char or a one-character literal. Fixed-font constants fold at compile time.
const sign = "ADDER"
var shown: Char = .space
when s = System.keyboard.stroke
if c = s.character() then
shown = c
end
end
System.screen.text[0][0..<5] <- sign
System.screen.text[12][20] <- shownPictures and Fonts
Adder lets you draw sprites, custom characters and bitmap art right in your source file as visual grids of text, which the compiler bakes directly into your compiled program. Art declarations usually use lists of strings where . leaves a pixel clear and X lights it up. A drive load can also supply a font, a shape or a fixed list of shapes while the program runs. A program can pack up to 256 distinct values of each art type.
When startup moves fixed art to its display location, Adder can reuse its packed copy's memory through a screen buffer or storage it already clears. Startup unpacks the art before filling or clearing that memory. Staging through a screen adds startup work and a small amount of code; art that cannot fit keeps its usual copy.
| Type | Made with | What it holds |
|---|---|---|
Glyph | Glyph([...]) | one character: 8 rows of 8 pixels |
Font | Font.uppercase, Font.lowercase, Font(fn(c) -> Glyph), Font(glyphs, fill:, map:), Font(file:, map:) | a font of 256 glyphs |
Shape | Shape([...]), Shape.square | a sprite's picture: 21 rows of 24 pixels, or of 12 multicolor pixels |
Picture | Picture([...]) | art for a canvas: rows of one width |
Sheet | Sheet(file:, color:, transparent:) | a PNG image that pictures are cut from |
Drawing | picture.place(...), picture.fill(...) | a picture at a place on a canvas |
When you draw a multicolor Shape or Picture, each pixel is twice as wide and chooses from four palette slots written ., A, X and B. Font(glyphs, fill:, map:) builds a complete font from a list of 256 glyphs (or a shorter list of 1 to 256 glyphs padded to 256 with fill: glyph), with an optional map: of 128 screen codes that tells the machine which glyph each Char displays. Font(file:) loads a raw 2,048-byte .bin or .chr character set file straight from your project folder. For art that changes by level, load a generated companion with System.drive[8].load(name) and an annotation such as Result of Font?, Result of Shape? or Result of [12 of Shape]?. Match nil, success(font) and failure(reason) to choose what the screen shows. Use the latest successful art; a later success from the same load may reuse earlier native slots. Separate loads keep separate sets available. See The System Device Tree for how to put your shapes, fonts and pictures up on the screen.
const ship = Shape([
"....AAAA....", "...AXXXXA...", "..AXXXXXXA..", ".AXXBBBBXXA.", "AXXBBBBBBXXA", "AXXBBBBBBXXA", ".AXXBBBBXXA.",
"..AXXXXXXA..", "...AXXXXA...", "....AAAA....", "............", "............", "............", "............",
"............", "............", "............", "............", "............", "............", "............"
])
System.screen.sprite[0] <- (x: 100, y: 100, shape: ship)If a row of pixel characters is the wrong width or contains an unrecognized character, the compiler points out the exact row with pixelAsset.
Fonts Built from the Machine's Letters
A game often needs a few tiles in an otherwise ordinary font. Font(fn(c) -> Glyph) builds a font one character at a time: the function receives each character and returns the glyph that character shows. Font.lowercase[c] and Font.uppercase[c] give the glyph a character shows in one of the machine's own fonts, so the rest of the characters can keep it.
const wall = Glyph([0xFF, 0x81, 0xBD, 0xA5, 0xA5, 0xBD, 0x81, 0xFF])
const floor = Glyph([0x00, 0x22, 0x00, 0x88, 0x00, 0x22, 0x00, 0x88])
const hangar_font = Font(fn(c) ->
match c
"#" -> wall
"." -> floor
else -> Font.lowercase[c]
end
)
System.screen.font <- hangar_font
System.screen.text[0][0..<9] <- "#..# Deck"The function is called once for every character the machine shows: the space, the digits and punctuation, A to Z, a to z and |. Each glyph goes where text looks for that character, so ScreenCode(c) and printed strings find it. A reversed cell (its screen code plus 128) shows the inverse of the glyph, as it does in the machine's fonts.
The compiler works the font out when the program compiles, so the function can read constants and its character but nothing that changes while the program runs. Font.uppercase[c] gives the glyph the uppercase font shows for c, so a lowercase letter gives its capital.
The program file never holds the machine's own glyphs. The program copies them from the computer's own character set: once at startup for a font it keeps in memory, and after each load for a font it loads from a companion file. The cost report shows the copy on the font's line, or on the line that loads it. Outside a font, Font.lowercase[c] is an ordinary glyph: a program that keeps one in a variable keeps a copy of that machine font in memory.
Indexing any font with a character gives the glyph that character shows: hangar_font[Char("#")] is the wall. Indexing with a number gives the glyph in that slot, as tile programs use it.
Enums
An enum defines a type with a fixed list of named cases, such as game states, directions or monster behaviors. Every enum name starts with a capital letter.
enum Mode
case title, playing, over
end
var mode: Mode = .title
when System.joystick[2].fire.pressed
mode = mode.next()
end
System.screen.border <- match mode
title -> .blue
playing -> .black
over -> .red
endWhen an enum's cases carry no extra fields, they stay in the order you listed them: < and > compare them by position, Mode.first and Mode.last give the two ends, and .next() steps forward from case to case, wrapping neatly from the last back to the first. A simple enum like this takes just one byte.
for name in Mode visits each case once in declaration order. Mode.count gives the fixed number of cases, and name.index gives its zero-based position. These members describe the cases, so changing a value associated with a case never changes their order.
Values associated with cases
An enum can give each case a value of a declared type. An enum of colors names the colors a picture uses:
enum Water: Color
case deep = .blue
case mid = .light_blue
case foam = .cyan
end
var selected: Water = .foam
const saved_name = Water.foamselected and saved_name hold the case. Inside a handler, const saved_color: Color = Water.foam saves its current color. Where Color is expected, qualified Water.foam reads the current color. Without that context it means the case. Water[selected] always reads the value belonging to the selected case; a variable holding a Water case does not turn into a Color implicitly.
Assign an associated value in a handler to change it for every use of that name:
enum Water: Color
case deep = .blue, mid = .light_blue, foam = .cyan
end
when System.keyboard.space.pressed
Water.foam = .white
endWater.foam remains the same case after this assignment. Two cases remain unequal even if their colors match. Compare Water[Water.deep] and Water[Water.mid] to compare their current colors. An alias shares the same cases and values; declare another enum when two pictures need independent colors.
Every case needs a compile-time initializer. The value type can also be a number, bool, character, bounded text, picture, fixed list, struct, enum, optional or capture-free pure function. Values must have a finite size and ordinary copying rules. Devices, events, jobs and service capabilities cannot be associated values. The compiler keeps unassigned cases constant, even when another case changes. Pure calculations and work can read those constants; pass changing values as explicit inputs. Helpers change an association only through an explicit mut parameter. Bindings can read current values but cannot drive a case with <-.
Use Water[name] as a destination when a loop applies a theme:
enum Water: Color
case deep = .blue, mid = .light_blue, foam = .cyan
end
const theme: [3 of Color] = [.purple, .light_red, .white]
when System.keyboard.return.pressed
for name in Water
Water[name] = theme[name.index]
end
endSee Canvas pixels for editable pictures that store these names and recolor without recalculating their pixels.
Cases can also carry named fields of their own. You build such a case by labeling its fields, and unpack those fields inside a match arm:
struct Spot(x: Number<0...319>, y: Number<0...199>)
enum Drag
case still
case moving(grab: Spot, column: Number<0...39>)
end
var drag: Drag = .still
var column: Number<0...39> = 0
when System.joystick[2].fire.pressed
drag = .moving(grab: (x: 10, y: 20), column: 4)
end
when System.screen.frame
match drag
moving(grab, column: chosen) ->
column = chosen
still ->
end
endAn enum with fields takes one byte for its case tag plus enough bytes to hold the fields of its largest case.
An enum with fields can also declare an associated value type. That value belongs to the case name independently of its fields: Drag[drag] reads it, while constructing .moving(...) still requires its fields. Such enums do not have count, index or enum iteration, because those operations would need to invent field values. Iterate a list of constructed values instead.
Structs
A struct groups related named fields into one value, such as a sprite's velocity, an enemy's coordinates or a high-score row. In its compact one-line form, you list the fields inside parentheses right after the struct's name. Any field can specify a default value with =, which steps in whenever a newly created struct value leaves that field out.
struct Speed(x: Number<-3...3>, y: Number<-3...3> = 0)
const speeds: [3 of Speed] = [(x: 1, y: 2), Speed(x: -1, y: 3), (x: 2)]
n: Number<0..<3> <- System.screen.frame.every(30).cycle()
s <- speeds[n]
System.screen.sprite[0] <- (x: 100 + s.x * 10, y: 100 + s.y * 10)When you create a struct value, you label each field you supply. You can write the type name out in front, like Speed(x: 1, y: 2), or write just (x: 1, y: 2) whenever the receiving spot already expects a Speed. A spot knows what struct type to expect when it is a typed var, a function parameter, a function's return value, a struct or enum field, an element of a typed list, a branch of an if or match, or a hardware sprite output. That expected type also flows right through an optional (Speed?), into a single value replicated across a whole list ([4 of Speed] = (x: 0, y: 0)), and into a typed map callback whose result is expected to be a list of structs. If you write an unnamed (x: 1, y: 2) where no struct type is expected, the compiler flags it with structNeedsContext, quotes the value back to you, and—when only one struct in your program has those field names—shows the exact named form to use. Reading a field is as simple as value.field, and a struct takes the sum of its fields' bytes in memory.
For richer types, the multi-line block form of struct can also hold mutable var fields and member functions (fn and mut fn), as Declarations explains. To keep structs self-contained, a struct's function reads only its parameters, the struct's own fields and the program's top-level constants; if it needs a program variable, binding or hardware device, pass that value in as an argument rather than reading it directly (operationScope).
A protocol names required fields and member functions. A type declares its promise with struct Marker: Positioned or enum Mode: Scored. A parameter typed with that protocol accepts a conforming concrete value, and each call uses the concrete type. A protocol cannot be a stored value's type.
Use a named field type such as (x: Number, y: Number) when a signature needs a small field shape without a separately named struct. Its values use the existing (x: 10, y: 0) spelling.
Built-In Structs
| Type | Fields |
|---|---|
Point | x 0 to 319, y 0 to 199 |
Sprite | x -24 to 487, y -50 to 205, shown, behind, x_expand and y_expand as bool, shape a Shape, color a Color, and method overlaps(other: Sprite): bool |
SpriteMulticolor | first and second as Color |
Tone | a note or frequency with sound parameters, made with Tone(...) |
Envelope | attack, decay, sustain and release |
Filter | cutoff 0 to 2047, resonance 0 to 15, low_pass, band_pass, high_pass and mute_voice_3 as bool |
Keystroke | key a Key, and shift, control, commodore and repeat, each a bool |
A sprite's x and y coordinates measure pixels from the top-left corner of the visible picture, and their negative lower bounds let a sprite glide smoothly onto and off every edge of the screen.
Lists
[n of T] is a fixed-length list holding n items of type T. Because small machines thrive on predictable memory layout, the length n is a whole number from 1 to 65,535 known at compile time (and may be a parenthesized calculation of constants). Elements can be of any type, including inner lists: [3 of [4 of Number<u8>]] gives you a neat 3-by-4 grid.
const rows = 3
var grid: [rows of [4 of Number<u8>]] = 0
const tune: [4 of Note?] = [.c4, nil, .e4, .g4]
when System.keyboard.space.pressed
grid[1][2] = 7
end
System.screen.text[0][0..<1] <- grid[1][2].digits(1)In memory, a list takes n times the byte size of a single element. Handing a single element value to a whole list fills every slot with that value—just as = 0 zeroes out every cell of grid above. The ++ operator splices two lists together as long as both lengths are known at compile time, even if their elements change while the program runs; the combined list has the sum of their lengths and a single shared element type:
const base = [1, 2, 3]
var extra: [2 of Number<u8>] = [7, 8]
joined <- base ++ extra
System.screen.border <- Color(joined[4] % 16)If a list's length falls outside 1 to 65,535, the compiler catches it with arraySize.
You can also write functions that accept a list of any length by using single-letter names for the length and element type in the parameter list, as Declarations shows:
fn keep(values: [n of T]): [n of T]
values
end
const numbers = keep([1, 2, 3])
const flags = keep([true, false])Turn to Expressions to see how to index a single element, slice a window of consecutive elements, or carve out a rectangular patch from a 2D grid.
Lists that grow
[up to N of T] is a list that holds from none to N items of type T. It keeps a live length beside its N places, so it grows and shrinks without leaving empty places behind. To keep the last N values of something, use a Ring of (N of T) instead: push drops the oldest value for you, and a small ring costs what shifting a fixed list by hand does. A fixed [N of T] list keeps all N places filled; a bounded one holds only what it was given. Start one empty with [] or with the items it begins with, and read xs.length, xs.capacity, xs.is_empty and xs.is_full without parentheses.
| Operation | What it does |
|---|---|
xs.append(item) | Add an item after the last one. A full list fails and keeps its items. |
xs.insert(item, at: i) | Put an item at position i, where 0 <= i <= xs.length; the items from i on move up one place. A full list, or a position past the length, fails and keeps its items. |
xs.remove(at: i) | Take out the item at position i, where 0 <= i < xs.length; the items after it move down one place. |
xs.clear() | Empty the list. |
xs[i], xs[i] = item | Read or replace the item at i; i is checked against the live length, so a position inside the capacity but past the last item stops the program. |
These are the words a String uses, with the same rules: every check runs before an item moves, so a failed change leaves the list as it was. An insert or a remove normally moves the items after its position as one block of bytes and makes no second copy of the list. For some private lists of large Strings, the compiler keeps a one-byte position table instead: edits move positions, reads do an extra lookup, and removal also preserves one spare line for saving. Whole-list copies, function arguments and drive operations still present the same ordered value and saved bytes. The cost report identifies lists that use the table and includes these costs. Other lists keep their usual storage. The items of a bounded list can be anything a list holds, including strings, and a member of an item works in place: lines[row].insert(character, at: column) changes only the line row names.
var crew: [up to 8 of String<16>] = ["Okafor", "Brandt"]
when System.keyboard.space.pressed
if not crew.is_full then crew.append("Moreau") end
end
when System.keyboard.delete.pressed
if not crew.is_empty then crew.remove(at: 0) end
end
System.screen.content <- Text(crew[crew.length - 1]).at(row: 0, col: 0).width(16)To empty one place of a list of optionals and leave the others where they are, assign nil to it: windows[2] = nil. remove always closes the gap, in a string and in a bounded list.
Walking. for item in xs visits the live items in order, none of the empty places, and for i in 0..<xs.length runs once for each live item and gives its position. Neither lets the body change xs while the loop goes through it by item; For Loops has the rules.
Helpers. The collection helpers of Expressions read only the live items of a list that grows: map, filter, count, sum, min, max, any, all, find, find_index, first, last, contains, reduce, scan, indexed_map and zip_with. A helper that gives a list gives a list that grows, and filter keeps only the items that pass, in order, with no empty places between them.
var crew: [up to 8 of String<16>] = ["Okafor", "Wu", "Brandt"]
fn long_name(name: String<16>): bool
name.length > 3
end
long <- filter(crew, long_name)
System.screen.content <- [Text(first(long) ?? "-").at(row: 0, col: 0).width(16), Text(long.length.digits(1)).at(row: 1, col: 0)]Slices. crew[a..<b] is the live items from a up to, not including, b, as a list that grows of the same capacity. It requires 0 <= a <= b <= crew.length and stops the program otherwise. A binding of a slice names the original items and follows the list; a var made from it keeps a copy; a slice cannot be assigned to.
Comparing. a == b and != on two lists that grow give one answer: the lists are equal when they have the same length and every live item of one equals the item of the other. Their capacities, and anything left in the places past the live items, do not matter. Use zip_with(a, b, fn(x, y) -> x == y) to compare item by item.
Writing one out. crew = [first, "Moreau"] fills the front of the list with the items it gives, whatever they hold, and sets the length to match; crew = [] empties it.
Parameters. A function that takes [up to n of T] accepts a list that grows of any capacity: n names that capacity, and T the type of its items. The callbacks of the helpers work inside such a function as they do anywhere.
On the disk. System.drive[8].save(name, crew) and System.drive[8].load(name) keep the live length with the items and give the same list back. A file that claims more items than the list's capacity has damaged contents: the load fails with .damaged and gives no value.
Function Types
A function type describes a pure calculation's inputs and result: fn(Digit): Digit takes one Digit and returns one Digit. The parameters in a type have positions, without names or labels. Two function aliases with the same resolved inputs and result describe the same type. A function type is concrete: it does not store a function that can choose a different type on each call.
| Type | Meaning |
|---|---|
fn(): Digit | no arguments, returning a Digit |
fn(Digit, bool): Digit | two positional arguments |
fn(Digit): fn(Digit): Digit | a function returning another function |
fn(Digit): Digit? | a function returning an optional Digit |
(fn(Digit): Digit)? | an optional function, unwrapped before calling |
fn([4 of Digit]): Digit | one complete four-element list argument |
The result takes the complete type after its colon, so nested function results group to the right. Parentheses group a type without changing it; use them before ? when the function itself may be absent.
type Digit = Number<0...9>
type Transform = fn(Digit): Digit
type MaybeTransform = (fn(Digit): Digit)?
fn flip(value: Digit): Digit
9 - value
end
const transform: Transform = flip
var chosen: MaybeTransform = transform
answer <- if callback = chosen then callback(3) else 0 end
System.screen.border <- Color(answer)A callback fits a slot when it accepts every input the slot permits and returns only values the slot permits. For a Digit-to-Digit slot, a callback accepting Number<0...255> and returning Digit fits; one accepting only 1...9 does not, because the slot allows zero. A callback explicitly returning Number<0...255> does not fit a Digit result, even if its current body happens to return three. Use an explicit checked wrapper when you need a narrower result.
This check follows numeric ranges and precision, enum and hardware identities, list sizes, optionals and nested function signatures. String capacity is part of its identity here: fn(String<4>): String<4> requires the same capacity in the supplied function's signature. A synchronous closure captures a local String's length and characters when the closure is created. It never drops a fraction, changes a named kind or adds a failing conversion to make a callback fit. Ordinary present values can fit an optional slot; an optional input cannot silently lose its possible nil. A pure callback can still fail its own arithmetic or declared result check.
Capture-free callbacks can be copied through ordinary constants, variables, bindings, lists, fields, optionals, arguments and results. Callbacks have no equality, ordering or identity test, including inside a list or struct; an optional callback still permits a nil presence test. Callback-containing values do not support temporal members such as .changed, .previous() or .history(), and cannot be event payloads, work/job data or queue data. Pool, Ring, Deck and Wave do not store callbacks in this increment; use an ordinary fixed list for capture-free callback choices. Functions as Values describes creation, inference and the shorter lifetime of callbacks that capture locals.
Optionals
Adding a question mark to any type—T?—makes it optional: it holds either a present value of type T or the missing value nil. In memory, T? takes just one extra byte beyond T to track whether a value is there.
var held: Number<u8>? = nil
when System.keyboard.space.pressed
held = 7
end
when System.keyboard.delete.pressed
if n = held then
held = n -| 1
end
end
shown <- held ?? 0
System.screen.border <- if held != nil then Color(shown % 16) else .black endYou have three clean ways to work with an optional value:
value ?? fallbackunwraps the value when present, or hands backfallbackwhen it isnil;value != nilandvalue == niltest whether a value is currently there;if name = value then,guard name = valueandwhen name = eventunwrap the value intonamefor the body block whenever it is present.
An optional is never a boolean condition on its own, so writing if held then triggers bareOptional. Checking flares[i] != nil also proves to the compiler that flares[i] holds a real value inside the then branch (and on the right-hand side of and), allowing you to call mutating operations directly on flares[i] there. Likewise, flares[i] == nil proves the value is present inside the else branch, and guard flares[i] != nil proves it for the remainder of the handler.
Events
An event—like System.keyboard.space.pressed or System.screen.frame—represents a moment in time rather than a stored value in memory. Some events fire as a pure pulse (Event), while others carry a fresh payload each time they happen (Event of T), such as System.keyboard.stroke carrying a Keystroke.
press: Event <- System.joystick[2].fire.pressed
stroke: Event of Keystroke <- System.keyboard.stroke
var presses: Number<0...9> = 0
when press
presses = presses +% 1
end
System.screen.text[0][0..<1] <- presses.digits(1)Because an event happens at moments rather than sitting in RAM, you can give it a name with a <- binding, whereas trying to store an event in a constant or a var triggers eventConstant. The Events and Handlers chapter shows all the ways your program can listen, filter and respond to events.
Results and Failures
When background work talks to an external device like a disk drive, the operation finishes either with the data you asked for or with a report of what went wrong. Result of T is a built-in enum with two cases: success(value: T) and failure(reason: Failure). Failure is itself an enum with the following cases:
not_present: the requested device or drive number is not attached or responding.not_found: the requested file name does not exist on the mounted disk.disk_full: no free sectors remain on the disk to store additional data.write_protected: the disk notch is protected or the virtual image is write-protected.damaged: Adder found truncated, corrupt or impossible file contents, such as a stored length above capacity.wrong_type: the file's header names a different type from the one you asked to load.device_error(code:): the drive reported an error, wherecodeis aNumber<u8>; code 74 means the drive is not ready.
Every Failure reason also provides a 40-character reason.message string (padded to 40 characters) suitable for displaying directly on the screen without manual string formatting. The two file checks say The file is damaged. and The file holds a different type. before the padding.
const reading: Result of Number<u8> = .success(value: 3)
System.screen.border <- match reading
success(value) -> Color(value)
failure(reason) -> .red
endBounded ASCII strings
String<N> holds up to N ASCII characters and a logical length. N is a fixed whole capacity in 0...65535, within ordinary memory and frame limits. Literals infer their decoded length; var name: String<32> = "" reserves room to grow. Bare String is a conversion name.
Assignment, parameters, results and String<N>(value) check the live length before publication. They preserve spaces and never truncate. Copies, a var or const made from a slice, and trimming keep snapshot values after their source changes. Spare storage is unobservable.
A fixed [N of Char] destination accepts a shorter literal or String<n> when n is at most N. Adder keeps the live characters and fills the rest with spaces. Bindings, assignments, arguments, results and if or match arms all follow this rule, as do screen rows and slices. An oversized literal or String capacity is refused with both lengths, even when a larger String currently holds fewer characters. Converting the text with ScreenCode(text) follows the same width rule for a fixed [N of ScreenCode] destination. Already constructed Char and ScreenCode lists keep their exact shapes.
var status: String<8> = "Ready"
message: [40 of Char] <- match status.is_empty()
true -> "Waiting"
false -> status
end
System.screen.text[10] <- messageconst codes: [40 of ScreenCode] = ScreenCode("READY")
System.screen.text[0] <- codesLiteral padding happens during compilation and adds no runtime work compared with writing the spaces yourself. A changing String uses the same bounded copy and space fill as s.padded(width: N); the cost report includes that work and any captured value. A shorter String in ordinary program memory uses paired copy and fill loops for destinations up to 255 characters. In a small program, row = input from String<8> to [40 of Char] uses 68 bytes of code with a static bound of 436 cycles; the complete frame bound is 464 cycles. The faster loops use extra code, and screen text also needs font conversion and display work. These are bounds, and a larger destination or a captured source can cost more.
.length reads the live length; .capacity gives the fixed maximum. s[i] reads or replaces a live Char. s[a..<b] slices the live characters with an exclusive end, as a list slices. trim, trim_start and trim_end remove ASCII 9...13 and 32 only at the selected edges. Equality compares one live sequence across capacities. starts_with, ends_with, equals_ignore_case and find(pattern, start:) support scanners; find returns an optional index. Case folding affects ASCII letters only.
| Operation | Result and checked boundary |
|---|---|
s.length, s.capacity, s.is_empty() | Live length, fixed capacity, or whether length is zero. |
s[i], s[i] = character | Read or replace an existing live character; require a whole index in 0..<s.length. |
s[a..<b] | The live characters from a up to, not including, b; require 0 <= a <= b <= s.length. An empty slice at the end is valid. A binding of a slice names the original characters and follows the string; a var or const made from it copies them. A slice only reads: replace a character with s[i] = character. |
s.trim(), s.trim_start(), s.trim_end() | Remove ASCII 9...13 and 32 from the selected edges; interior characters remain. |
s == t, s != t | One Boolean for the live character sequences, including trailing spaces, across capacities. |
s.starts_with(t), s.ends_with(t) | An empty pattern matches every string. |
s.find(t, start: a) | Optional first index at or after a; require 0 <= a <= s.length. Empty pattern returns a; missing pattern returns nil. |
s.equals_ignore_case(t) | Compare live sequences after folding ASCII A...Z only. |
s.append(t) | Append a String or Char to a mutable place if the complete result fits. |
s.insert(t, at: i) | Put a String or Char before index i of a mutable place if the complete result fits; require 0 <= i <= s.length. i == s.length appends. Only the characters from i on move. |
s.remove(at: i) | Take out the character at i of a mutable place and close the gap; require 0 <= i < s.length. Only the characters after i move. |
s.truncate(length: n), s.clear() | Keep the first n characters, or none; require a whole 0 <= n <= s.length. |
A page of text edits its lines where they lie. This program types a letter into the line under the cursor, deletes the one before it, and shows that line:
var lines: [4 of String<16>] = ["coat", "", "", ""]
var row: Number<0...3> = 0
var col: Number<0...15> = 1
when System.keyboard.space.pressed
lines[row].insert(Char("o"), at: col)
col = col +| 1
end
when System.keyboard.delete.pressed
if col > 0 then
col = col - 1
lines[row].remove(at: col)
end
end
System.screen.content <- Text(lines[row]).at(row: 0, col: 0).width(16)Walking a String. for c in s visits the live characters in order, giving c the type Char; an empty String never runs its body, and the body cannot change s. for i in 0..<s.length runs once for each live character and gives its position i, reading the length once when it starts. Both read the String where it lies, so a function that scans its String parameter makes no copy of it. For Loops has the rules and a program.
Bounds and operand expressions run in written order. An ordinary failed bound stops evaluation at that source position; a failed store leaves its previous complete value. Retaining a slice or trimmed value, returning it from a function, or passing it before a later mutation keeps the captured characters.
++ joins String, Char and fixed Char-list values once in written order. if and match can combine String and Char-list arms: a fixed N-character destination fills fitting String arms to [N of Char], while an ordinary String choice uses the largest arm capacity. append, insert(at:), remove(at:), clear and truncate(length:) act on mutable String places, in place and at a computed index such as lines[row] alike. A String stays a String: it shares these words with a bounded list where they mean the same, and a literal is never a list. Failed construction or mutation preserves the previous complete value, so an insert into a full string or at an index past the length changes nothing. Fixed lists keep their own shapes and compare as whole values: use String(chars, length:) to capture their prefix and s.padded(width:) for an explicitly space-filled Char list.
Numbers produce signed decimal strings with value.format(). Fractional values use their exact stored 1/256 steps, with at most eight places and no redundant fractional zeros. format(decimals: p) accepts a fixed p in 0...8, rounds ties away from zero, emits exactly p places, and suppresses a minus on rounded zero. digits(k) keeps its fixed, zero-filled Char-list contract.
Number.parse(text) gives Number?; use a numeric alias such as type Amount = Number<i8.8> and Amount.parse(text) to select another domain. Parse consumes the complete live string without trimming. It accepts one optional sign and decimal digits, plus a nonempty fraction for fractional targets. Malformed text and exact values outside the selected domain give nil. Exact domain checking happens before nearest-1/256 rounding, with ties away from zero; evaluation failures producing the input still stop normally.
Interpolation such as "Hello \(name), score \(score)" builds one String. String, Char and fixed Char-list holes insert their content; Number holes use format(). Holes retain ordinary expression checks and source locations. Use explicit conversions for lists and other kinds.
Game Collections and Fast Primitives
Action games and arcade simulations need dynamic entities, circular buffers, stacks and collision checks that run within tight frame budgets without allocating dynamic memory while playing. Adder provides dedicated zero-allocation game primitives designed to stay fast and compact in memory:
| Type | Declared with | Purpose |
|---|---|---|
Pool of (n of T) | Pool() | Bounded pool of up to n active entity records |
Ring of (n of T) | Ring(initial: ...) | Circular history of n items, overwriting the oldest |
Deck of (n of T) | Deck() | Bounded stack of up to n items |
Rect | Rect(x:, y:, w:, h:) | 2D axis-aligned box with fast collision testing |
Cooldown | Cooldown(period: p) | One-byte countdown timer |
Wave of (n of T) | Wave([...]) | Fixed sequence of spawn specifications in program data |
Flags of Enum | Flags() | Compact one-byte bitfield for an enum of up to 8 cases |
Entity Pools
A Pool of (n of T) holds up to n active entities of struct type T, where n is a number up to 255. Instead of allocating memory dynamically, the pool sets aside memory for each field across parallel columns. When an entity struct has a field whose range excludes zero (like y: Number<40...240>), the compiler automatically uses zero as a missing tag, saving memory and speeding up presence checks.
A pool offers seven clear operations:
pool.spawn(item: T) -> boolinsertsiteminto the first open slot and returnstrue, or returnsfalseif allnslots are occupied;pool.step(with: fn(item: T) -> T?)updates each active entity in place, freeing any slot whose step function returnsnil;pool.clear()frees every slot at once;pool.countreads how many slots currently hold an active entity;pool.is_emptyandpool.is_fullcheck whether the pool has zero ornactive entities;pool.any(where: fn(item: T) -> bool)andpool.first(where: fn(item: T) -> bool)search across active entities;pool.slotsexposes the underlying[n of T?]list of slots, ready to bind straight to hardware sprites.
struct Laser(x: Number<0...319>, y: Number<0...199>)
var lasers: Pool of (4 of Laser) = Pool()
var cd: Cooldown = Cooldown(period: 8)
fn move_laser(l: Laser): Laser?
if l.y > 10 then Laser(x: l.x, y: l.y - 4) else nil end
end
when System.joystick[2].fire.pressed
if cd.trigger() then
lasers.spawn(Laser(x: 160, y: 180))
end
end
when System.screen.frame
cd.tick()
lasers.step(with: move_laser)
end
System.screen.border <- if lasers.is_empty then .black else .green endstep, any and first accept named functions, typed function values and inline fn expressions. A saved callback can be reused across calls:
struct Spark(x: Number<0...319>, y: Number<0...199>)
fn lift(spark: Spark): Spark?
if spark.y > 0 then Spark(x: spark.x, y: spark.y - 1) else nil end
end
const advance: fn(Spark): Spark? = lift
var sparks: Pool of (4 of Spark) = Pool()
var any_low: bool = false
when start
sparks.spawn(Spark(x: 160, y: 180))
end
when System.screen.frame
sparks.step(with: advance)
const cutoff = System.paddle[1]
any_low = sparks.any(where: fn(spark) -> spark.y > cutoff)
end
System.screen.border <- if any_low then .yellow else .black endAn inline function can also snapshot a local sample, using the same capture rules as other callbacks. Capture an ordinary local value; a Pool itself cannot be captured. The receiver and callback expression are each acquired once, even when the Pool is empty. Active slots are visited from highest index to lowest. first returns the first matching value in that order, and both queries stop at a match.
Each successful step result replaces its slot immediately. If a later callback or boundary check fails, earlier replacements survive and the failing and remaining slots stay unchanged. String arguments and results use their live lengths for capacity checks. These in-place updates have different publication rules from a fixed-list map, which replaces the complete result at once.
Rings and Decks
A Ring of (n of T) keeps a circular history of n items. Calling ring.push(item) adds a fresh value, overwriting the oldest value once all n places are filled. .newest and .oldest inspect the ends, while .sample(k) reads backwards from newest (0 is newest, n - 1 is oldest).
A Deck of (n of T) provides a bounded last-in, first-out stack for up to n items:
deck.push(item) -> boolpushes an item, returningfalseif already full;deck.pop() -> T?removes and returns the top item, or returnsnilwhen empty;deck.peek() -> T?inspects the top item without removing it;deck.clear(),deck.count,deck.is_emptyanddeck.is_fullinspect or reset the stack.
Rectangles and Collision
A Rect(x:, y:, w:, h:) represents a 2D axis-aligned bounding box. Calling box1.overlaps(box2) tests whether two rectangles intersect. When width and height are known constants, the compiler tests overlap in only two branches. box.contains(px, py) tests whether a point lies inside the rectangle.
Cooldowns, Waves and Flags
A Cooldown(period: p) tracks an 8-bit frame countdown. cd.tick() steps the counter down by one each frame until it reaches zero. cd.is_ready reports whether the counter has reached zero, and cd.trigger() checks readiness, reloads the period, and returns true if it fired.
A Wave of (n of T) defines a fixed table of spawn records. Because waves are declared as constants, the compiler bakes the data straight into program storage with no variable memory required, and wave.at(index) reads any record.
Flags of Enum packs up to 8 cases of an enum into a single byte. .add(case), .remove(case) and .toggle(case) manipulate flags with single instructions, while .has(case) checks whether a flag is set.
enum Status
case poisoned, frozen, shielded
end
struct SpawnSpec(x: Number<0...319>, delay: Number<u8>)
const spawns: Wave of (2 of SpawnSpec) = Wave([(x: 20, delay: 10), (x: 40, delay: 20)])
var trail: Ring of (4 of Point) = Ring(initial: Point(x: 0, y: 0))
var deck: Deck of (4 of Number<u8>) = Deck()
var flags: Flags of Status = Flags()
var box1 = Rect(x: 10, y: 20, w: 8, h: 8)
var box2 = Rect(x: 14, y: 24, w: 8, h: 8)
when System.screen.frame
trail.push(Point(x: 100, y: 50))
deck.push(42)
flags.add(.poisoned)
end
hit <- box1.overlaps(box2)
inside <- box1.contains(12, 22)
System.screen.border <- if hit and flags.has(.poisoned) then .green else .red endReceipts
Successful saves and sequential file writes return a Receipt inside Result of Receipt. A receipt has one field, bytes: Number<u16>, recording the number of bytes transferred. A failure instead carries a Failure reason:
const saved: Result of Receipt = .success(value: Receipt(bytes: 42))
System.screen.text[0][0..<5] <- match saved
success(value: receipt) -> receipt.bytes.digits(5)
failure(reason) -> "ERROR"
endUse the surrounding result's success and failure cases to test the outcome; a receipt has no separate success flag or error code. Saving State shows the drive call that produces it.
Jobs and Streams
A computed Job of T captures a work calculation's inputs and continuation. Bind the call with <- to run it in the time left each frame and receive T?, or keep a captured job in a var and call resume() or finish() from a handler. resume() returns T?, absent until completion; finish() finishes the remaining work and returns T when its complete cost fits. Give each job one driver.
Computed jobs and their scheduled result bindings expose read-only progress: T? and running: bool. Progress is the latest complete value offered by the work, sampled at the beginning of the display frame; it is separate from the final answer. A captured computation keeps its remaining state private. See Work and Work Progress.
Storage saves and file writes return Job of Result of Receipt; their .result is optional until the operation finishes, then contains success or failure. Disk transfers can pause normal updates while the drive is busy, so the computed-work spare-time guarantee does not apply to them.
System.drive[d].file(name).read(capacity: n) produces a byte stream, Stream of Number<u8>, with a buffer of 1 to 255 bytes. Passing that stream to another file's write or append copies it through the bounded buffer, even when the file is larger. See File Streams.
Resultless Action Types
action(Number<u8>) describes a synchronous action accepting one byte value and returning no value. action() takes no parameters. Actions and pure fn(...): Result values are distinct callable types. A parameter expecting a narrow domain may safely receive an action accepting a wider domain; every possible argument still needs to fit. Actions may be forwarded synchronously, with immutable snapshot and static service capability lifetimes checked at each use. See Actions and do for examples.
Expressions
Whenever your program adds two scores, checks whether a sprite has reached the edge of the screen, or picks a fresh border color, it uses an expression. An expression is any formula or recipe that works out a value.
Before your program ever starts up, the compiler looks over every expression you write. It knows the exact type of every part, and for numbers it also tracks the lowest and highest values the calculation could possibly reach. If two parts do not belong together—say, trying to add a color to a number—the compiler catches the mix-up right away so you can fix it before running.
Operators and Their Order
When you string several operators together in one expression, Adder needs to know which ones bind first—just like multiplication comes before addition in everyday math. The table below lists all the operators from the tightest grip at the top to the loosest at the bottom. Operators sitting on the same row have equal strength and work from left to right.
| Operators | Meaning |
|---|---|
. [...] (...) after a value | members, indexes and calls |
- before a value | negation |
* / % | multiplication, division and remainder |
+ - +% -% +| -| ++ | addition and subtraction, and joining lists |
... ..< | ranges |
?? | a fallback for nil |
== != < <= > >= | comparisons |
not | the opposite of a yes-or-no value |
and | both |
or | either |
|> :> | passes the value to the next function |
when | an event filter, described in Events and Handlers |
Because of this order, -a * 2 means (-a) * 2, a + b * 2 means a + (b * 2), and not a == b means not (a == b). Whenever you want a different order—or just want to make your intent unmistakable at a glance—wrap that part in parentheses (...) so it runs first.
var a: Number<0...9> = 2
var b: Number<0...9> = 3
var paused: bool = false
result <- a + b * 2 // 8
grouped <- (a + b) * 2 // 10
moving <- not paused and a != b // (not paused) and (a != b)
System.screen.border <- if moving then Color(result) else Color(grouped % 16) endTwo small combinations ask you to spell out what you mean:
- Comparisons do not chain together in a row. Writing
a < b < craiseschainedComparison; spell out both halves asa < b and b < c. - A range (
...or..<) and the??fallback operator do not mix naked in the same expression. The compiler flags that withparenthesizeand asks you to add parentheses around whichever part should happen first.
Arithmetic
The five classic math operators—+, -, *, / and %—work on any two numbers. You can freely mix numbers of different storage formats, and if you combine a whole number with a fraction, the result becomes a fraction so nothing after the point is lost. If you accidentally hand an arithmetic operator something that is not a number, such as a Color or a bool, the compiler stops and lets you know.
Results and Their Ranges
One of Adder's friendliest tricks is that intermediate math inside an expression does not silently wrap around behind your back. Instead, the compiler works out the true range of each step from the ranges of the numbers going in. If a and b can each hold 0 through 9, then a + b spans 0 to 18, a - b spans -9 to 9, and a * b spans 0 to 81. It even notices when a number is multiplied by itself: a * a is a square, so its range never dips below zero! Adder then picks the smallest storage format that fits that full range, keeping the calculation itself safe from overflow.
var side: Number<1...20> = 1
area <- side * side // 1 to 400, in two bytes
when System.keyboard.space.pressed
side = side +% 1
end
System.screen.text[0][0..<3] <- area.digits(3)If an expression grows so wide that no storage format in the machine can hold its range—for instance, adding two full-range Number<u16> values in a binding—the compiler flags rangeNoRepresentation, points out the widest operand, and suggests giving it a tighter range.
The default number plays by a slightly different rule. Whenever either side of an operation is a plain, unannotated Number, the result is also a default Number spanning -32,768 to 32,767, and the program checks every step as it runs. Keep this in mind for formulas like (x + y) / 2: if x and y are default numbers holding 30,000, the addition itself steps past 32,767 and halts the program before / 2 gets a chance to bring the answer back down. Whole-number multiply then divide has one exception: a * b / c keeps the exact product privately and checks the final quotient.
When an arithmetic expression is made entirely of constants, the compiler does the math at compile time and bakes in the exact answer.
Checked Arithmetic
What happens when a calculation finishes and you store the answer into a place with a specific range—a variable, a struct field, a function parameter, a list element, or a typed binding? There are three cases:
- Guaranteed to fit: When the compiler can prove from the ranges that the result always fits, it emits no runtime check at all—your code runs at full speed.
- Guaranteed to miss: When the compiler can see that the answer can never fit, it catches the mistake right away with
literalDoesNotFitfor a constant orrangeExceededfor a calculation. - Might or might not fit: When the expression's possible range is wider than the destination, Adder inserts a safety check each time the value is stored. If a number steps out of bounds while you play, the program halts cleanly and prints the offending line on the screen instead of corrupting your game state.
var lives: Number<0...3> = 3
when System.keyboard.space.pressed
lives = lives - 1 // the fourth press stops the program here
end
System.screen.text[0][0..<1] <- lives.digits(1)Even better, testing a number in an if condition narrows its known range inside the branch! Inside if lives > 0 then, the compiler knows lives is at least 1, so lives - 1 is guaranteed to stay within 0...2 and needs no runtime check at all. Any check that does stay in the program takes a handful of bytes and cycles, which you can inspect anytime in the cost report.
Wrapping and Clamping
In arcade games and demos, you often want a counter to loop smoothly back to the start or stop cleanly at a wall without writing an if statement. Adder gives you dedicated operators for both:
+%and-%wrap: step past one end of the range and you come right back in from the other end, like a color wheel or an asteroid drifting across the screen edge.+|and-|clamp: step past one end of the range and you stop right at the boundary, like a paddle hitting the wall or a volume knob turned all the way up.
Neither wrapping nor clamping ever halts your program.
| Operator | Result of 14 op 3 in Number<0...15> | Result of 1 op 3 in Number<0...15> |
|---|---|---|
+% | 1 | 4 |
-% | 11 | 14 |
+| | 15 | 4 |
-| | 11 | 0 |
Both pairs use the declared range of the destination receiving the value—whether that is a variable, a list element, a field, a parameter, or a typed binding. They follow your logical range rather than the underlying byte size, so a Number<0...9> wraps cleanly from 9 back to 0, not at 255. Because they need a target range to know where the ends are, using them in a place that declares no range—such as an untyped binding or inside a conversion like Color(...)—triggers operationNeedsRange.
var hue: Number<0...15> = 0
var level: Number<0.0...1.0> = 0
when System.screen.frame
hue = hue +% 1 // 15 wraps to 0
level = level +| 0.125 // stays at 1.0
end
System.screen.border <- Color(hue)Musical notes have a fixed keyboard span and do not wrap around from top to bottom, so using +% or -% on a Note raises noteWrap. You can still add or subtract a whole number from a Note (or clamp with +| and -|) to shift it by that many semitones, and subtracting one Note from another gives you the distance between them in semitones.
Division and Remainder
/ divides two numbers and drops any remainder toward zero: 7 / 2 gives 3, and -7 / 2 gives -3. % gives the remainder left over after division, keeping the sign of the left-hand number: 7 % 3 is 1, and -7 % 3 is -1.
Dividing by a constant zero is caught immediately with divisionByZero. If the divisor is a variable or expression that could become zero while the program runs, Adder checks it before dividing and halts on that line if zero ever shows up.
Multiply Then Divide
Write a * b / c when a whole-number product can exceed the ordinary range but the quotient fits. Adder reads and checks each input as a signed 16-bit whole number, from -32768 to 32767. It keeps the exact signed 32-bit product privately, divides by c, and drops the remainder toward zero.
const ratio = 30000 * 2 / 2 // 30000
const negative = -7 * 1 / 2 // -3
const wider: Number<u16> = -32768 * -1 / 1 // 32768Inputs are read, checked and captured once from left to right. After every input passes, a zero c stops at the divisor's line. The quotient must fit its whole-number destination; without one, it must fit signed 16 bits. A failed check stops before storing the answer, and no public 32-bit value escapes.
When b and c are the same nonzero constant, as in n * 2 / 2, the answer is n itself, so Adder reads n and checks it against the destination without the 32-bit multiply and divide. Fractions and lists keep their usual arithmetic rules.
Parentheses around the product, (a * b) / c, keep the same exact calculation. A product stored in a separate declaration keeps its ordinary check. So do calculations inside any input: (a + b) * 2 / c can still fail at a + b before c is read.
Fractions
A fractional number measures values in fine steps of 1/256. Adding and subtracting fractions is completely exact. Multiplying or dividing fractions works out the answer in steps of 1/256 and drops any leftover sub-step toward zero.
Conversions
Adder checks numeric ranges wherever a value is assigned or passed, and admits whole numbers into fractional places when they fit. To change a value's kind, round a fraction, or request a narrower numeric type inside an expression, write that step explicitly.
Number Conversions
Use any number type as if it were a function to convert a value into that type. Writing Number<u8>(v), Number<0...15>(v), or Number(v) gives you v expressed in that target type.
var wide: Number<0...300> = 0
var shade: Color = .red
byte <- Number<u8>(wide) // checked: stops above 255
nibble <- Number<0...15>(byte)
code <- Number<u8>(shade) // a color's number, 2 for red
System.screen.border <- Color(nibble)
System.screen.text[0][0..<3] <- code.digits(3)If the compiler cannot prove at compile time that v always fits inside the target range, the conversion checks it at runtime. If the compiler can see that v definitely lies outside the target range, it points that out immediately with conversionOutOfRange. And if you try to pass a fractional number directly into a whole-number type, it stops with conversionDropsFraction so you can choose how you want to round it.
Going the other way—placing a whole number into a fractional type—needs no conversion at all as long as its range fits. To turn a fraction into a whole number, pick one of the three rounding functions below.
The machine's built-in named sets convert from numbers using their own type names in the very same style, such as Color(n) or Char(65).
Dropping a Fraction
When a sprite's smooth fractional position needs to snap to a character cell or pixel coordinate, call floor(), round(), or ceil() to turn the fraction into a whole number:
| Function | Rounds | 2.5 gives | -2.5 gives |
|---|---|---|---|
floor() | down | 2 | -3 |
round() | to the nearest, halves up | 3 | -2 |
ceil() | up | 3 | -2 |
The compiler rounds the ends of the number's range the exact same way, so round() on a Number<-2.5...2.5> produces a whole number with range -2...3. Calling any of the three on a number that is already whole simply returns it unchanged.
var x: Number<0.0...39.75> = 0
column <- x.floor()
nearest <- x.round()
when System.screen.frame
x = x +% 0.25
end
System.screen.text[0][column] <- ScreenCode.block
System.screen.text[1][0..<2] <- nearest.digits(2)Other Number Functions
Every number also responds to a handy set of built-in helpers:
| Function | Result |
|---|---|
n.abs() | the size of n without its sign |
n.sqrt() | the square root of a whole number from 0 to 65,535, rounded down |
n.clamp(lo...hi) | n held within lo...hi (or lo..<hi), with range Number<lo...hi> |
n.wrap(lo...hi) | n wrapped around lo...hi (or lo..<hi), with range Number<lo...hi> |
n.sine(lo...hi) | one full sine wave over n in 0...255, scaled to Number<lo...hi> |
n.digits(k) | k characters of n in decimal, with leading zeros, a [k of Char] |
n.lo and n.hi | the low and high Number<u8> bytes of any two-byte whole number (Number<u16> variables also allow v.lo = ... and v.hi = ...) |
Number.min(a, b) and Number.max(a, b) | the smaller and the larger of two numbers |
a * b / c | an exact private whole-number product, then a quotient truncated toward zero and checked against its destination |
n.clamp(lo...hi) and n.wrap(lo...hi) bound a whole number right inside an expression and narrow its type to that exact range, so (x + dx).clamp(24...320) or (frame + offset).wrap(0..<8) flows straight into a sprite coordinate or list index without a separate variable. n.sine(lo...hi) maps a byte angle 0...255 onto a whole-number range lo...hi (or lo..<hi) in -128...255 (hi - lo <= 255), starting at the midpoint at 0, peaking at hi around 64, and reaching lo around 192. Constant tables such as map(0..<256, fn(i) -> i.sine(0...63)) fold completely at compile time. n.digits(k) is the classic way to print a live score or timer onto the screen: it turns n into a [k of Char] padded with leading zeros (like "0042" for 4 digits), checking at runtime that n is between 0 and the largest k-digit number. If you want to call a dot-function directly on a number literal, wrap the number in parentheses first—write (15).sqrt() rather than 15.sqrt(), which the compiler flags with numberMember because the dot looks like a decimal point.
Bit Operations
Under the hood, a Number<u8> is a neat row of 8 switches (bits 0 through 7, counting from the right) and a Number<u16> is a row of 16 (0 through 15). Packing flags, dungeon doors, or bitmasks into a single byte is a beloved 8-bit craft, and Adder gives you clear, readable functions to inspect and flip those bits. Every bit function returns a fresh value and leaves the original number untouched.
| Function | Result |
|---|---|
v.bit_is_set(p) | true when bit p is on |
v.set_bit(p) | v with bit p on |
v.clear_bit(p) | v with bit p off |
v.toggle_bit(p) | v with bit p flipped |
v.bitwise_and(mask) | the bits on in both |
v.bitwise_or(mask) | the bits on in either |
v.bitwise_xor(mask) | the bits on in exactly one |
v.bitwise_not() | every bit of the width flipped |
v.shift_left(n) | the bits moved n places left, filling with zeros |
v.shift_right(n) | the bits moved n places right, filling with zeros |
A bit position or shift count runs from 0 to 7 on a Number<u8>, and from 0 to 15 on a Number<u16>. Better yet, you can pass a case from a fieldless enum as a bit position—Adder uses its position in the enum's declaration (0, 1, 2, ...), giving your bit flags self-documenting names! Bits shifted past either end of the number simply drop off, so Number<u8>(0x81).shift_left(1) becomes 2. Any mask you pass to bitwise_and, bitwise_or, or bitwise_xor must fit within the receiver's 8-bit or 16-bit width.
enum Path
case north, east, south, west
end
var open_paths: Number<u8> = 0b0000_0101
north_open <- open_paths.bit_is_set(.north)
either <- open_paths.bitwise_and(0x05) != 0
when System.keyboard.e.pressed
open_paths = open_paths.toggle_bit(.east)
end
System.screen.border <- if north_open and either then .green else .red endBit operations only work on exact 8-bit or 16-bit unsigned values (Number<u8> or Number<u16>). Calling them on any other number triggers bitwiseReceiver—just convert the number to Number<u8> or Number<u16> first. If a constant bit position, shift count, or mask steps outside the width of the number, the compiler catches it with bitwiseArgument; if the position or count changes while the program runs, Adder checks it on the spot.
Comparisons and Yes-or-No Values
Comparisons
The six comparison operators—==, !=, <, <=, > and >=—compare two values and hand back a bool (true or false). You can compare any two values that share the same kind:
- any two numbers, regardless of their ranges or storage formats;
- two values from the same named set, such as two
Colorvalues or twoCharvalues; - two cases from the same
enum.
The ordering operators (<, <=, > and >=) compare numbers by their value, named sets by their underlying machine numbers, and fieldless enums by the order their cases appear in the enum declaration. Two bool values can be tested for equality with == and !=. Structs cannot be compared directly; trying to compare structs or mismatched types triggers cannotCombine.
Two lists of the same size compare as whole values with == and !=: a == b is true when every place in a equals the place in b, and false as soon as one differs. The answer is one bool, not one for each place, and != is its opposite. The places can hold numbers (in any range), characters, names from one group, bool values, Strings, optionals, structs (which compare field by field inside a list), or lists of those; Strings compare by their text. Lists of different sizes raise arrayShapes, and lists whose places have no equality, such as an enum that carries fields, raise cannotCombine. When you want one answer for each place instead, pair the places yourself with zip_with(a, b, fn(x, y) -> x == y).
Two lists that grow compare the same way over their live items: they are equal when they have the same length and every pair of live items is equal, and capacity and the places past the length do not matter.
What if you compare a list against a single value? Adder pairs the value with every place and hands you back a list of bool values, as Operations Over Lists explains.
and, or and not
and, or and not combine and flip bool values. Both and and or are short-circuiting, meaning they stop as soon as the outcome is settled: in a and b, if a is already false, Adder skips working out b. These operators want real yes-or-no values, not numbers: handing a number to not triggers notNeedsBool, and handing a number to and or or triggers needsBooleans.
You can also use and and or to combine events, as shown in Events and Handlers.
Optionals and ??
Because an optional (T?) might hold nil, you can compare it with == and != against nil or against another optional of the same type when its values support equality. An optional callback permits only nil presence checks; callbacks and aggregates containing them have no value equality. Comparing an optional directly to a plain, non-optional value raises optionalCompare.
When you want to unwrap an optional and supply a default whenever it is empty, reach for the ?? fallback operator: value ?? fallback gives you the value inside the optional when one is present, or fallback when the optional is nil. Because fallback is a plain value of the inner type, the result of value ?? fallback is guaranteed never to be nil. Using ?? on a value that is not optional in the first place triggers coalesceNeedsOptional.
var held: Number<u8>? = nil
var other: Number<u8>? = 5
same <- held == other
present <- held != nil
shown <- held ?? 0
when System.keyboard.space.pressed
held = 7
end
System.screen.border <- if same or present then Color(shown % 16) else .black endAn optional is not itself a bool, so writing if held then triggers bareOptional—write if held != nil then (or unwrap it with if v = held then in a statement) instead.
Lists
List Values
Write a list by placing its elements inside square brackets, separated by commas: [2, 3, 5, 7]. For a list of numbers, the element type spans from the smallest number in the list to the largest; for other values, the list takes the type of its first element. When you store the list into a place that already declares a list type, every element takes that declared element type instead. Every list in Adder has a fixed, non-zero size: an empty [] is flagged with emptyArray, and a list whose length does not match its destination is flagged with wrongLength.
Two handy shorthands also build lists for you:
- A range used as a value, such as
0..<4, expands into the list of numbers it spans:[0, 1, 2, 3]. Char("HI")makes a fixed list of ASCII characters,[2 of Char]. The string literal"HI"itself is a boundedString<2>;s.padded(width: N)makes a fixed Char list from a live string.
A struct value, written in parentheses with labeled fields like (x: 10, y: 20), is described in Structs.
const primes = [2, 3, 5, 7] // four numbers, each from 2 to 7
const tune: [3 of Note] = [.c4, .e4, .g4]
steps <- 0..<4
System.screen.border <- Color(primes[1] + steps[2])Indexes
Write xs[i] to pick out element i of xs, counting from 0 at the front. The index must be a whole number: passing a fraction triggers indexNotInteger, and passing a constant index outside the list's bounds triggers indexOutOfBounds. When i changes at runtime and its range could step outside the list, Adder checks i before touching memory and stops cleanly on that line if it goes out of bounds.
On a bounded list [up to N of T] the index is checked against the live length, not the capacity: xs[i] stops the program when i is not below xs.length, and xs[i] = item replaces an item that exists. See Lists that grow.
For quick access to the ends of a list, first(xs) and last(xs) give you its physical first and last slots. An absent endpoint stays nil; these helpers do not search for another present value. A two-dimensional grid is simply a list of row lists, so grid[row][col] picks out one cell from one row. And if you have a list of structs, asking for a field gives you a list of that field across every element: corners.x gives you the list of every corner's x coordinate.
const grid = [[1, 2, 3], [4, 5, 6]]
var row: Number<0...1> = 0
var col: Number<0...5> = 0
corner <- grid[row][2]
when System.keyboard.space.pressed
row = row +% 1
col = col +% 1
end
System.screen.border <- Color(corner + first(last(grid)))
System.screen.background <- Color([1, 2, 3, 4][col % 4])Windows
Put a range inside the brackets to read or update a window of consecutive places in a list. Use a window to scroll a banner across the screen or update several columns at once. For example, xs[2..<6] is a window of four elements starting at index 2.
Every window has a fixed length known at compile time, even when its starting index moves from frame to frame. When the start is a constant, the end is a constant too (xs[2..<6]); when the start is a changing expression a, write the end as a plus a constant offset, such as xs[a..<(a + 4)] or xs[a...(a + 3)]. If the compiler cannot tell the window's fixed length, it flags sliceLengthUnknown; if a constant window reaches past the end of the list, it flags sliceOutOfBounds. When a sliding window's start could step past the list at runtime, Adder checks the start index once when the window is formed. A window's start and end only name places, because each call you write runs once and a window needs a single start: a call there that changes something, draws a random number or keeps a count is flagged sliceStartEffect. Run it first and slice from its name, with const origin = advance(mut pos) and then xs[origin..<(origin + 4)]; a call that keeps a count goes in a binding instead, as in origin <- System.screen.frame.every(8).cycle(0..<5), because a const refuses a remembered value.
const sign = Char(" ADDER SCROLLS A LONG SIGN ACROSS THE TOP ROW ")
left: Number<0...20> <- System.screen.frame.every(8).cycle()
System.screen.text[0] <- sign[left..<(left + 40)]A window reads the underlying list in place. A name bound to a window of mutable or mapped memory names those same places, whether its start is fixed or changing. It needs no value buffer, and a handler writes through it into the parent list. A matching type annotation keeps the same window; a different shape or element type is refused with sliceBindingType.
var cells: [4 of Number<u8>] = [1, 2, 3, 4]
live: [2 of Number<u8>] <- cells[1..<3]
var saved = live
when start
live[0] = 9
end
System.screen.border <- Color(live[0])
System.screen.background <- Color(saved[0])The border reads nine from cells[1]; the background reads two from the copy in saved. A var initialized from a window holds its own values. Constant lists and computed bindings remain read-only.
A window declared in a case has the case's scope. It follows a case-local variable's fresh initialization each time the case starts. A mutable function can borrow a window of a variable list or one row of a rectangle under the ordinary mut rules. Whole rectangles and mapped device places cannot be passed to ordinary mutable functions; write the rectangle directly, borrow its rows, or use a device operation that accepts that mapped place.
See Statements for more on writing into windows.
Rectangles
On a two-dimensional list of rows, you can slice both directions at once by placing two ranges inside the brackets, separated by a comma—rows first, then columns. grid[r..<(r + 2), 1..<3] carves out a 2-by-2 rectangle: a list of two rows, where each row is a two-element window. Both ranges follow the same fixed-length window rules above. Because a rectangle index always slices both dimensions, both parts inside [..., ...] must be ranges; if either one is a single index, the compiler flags rectangleRanges—to take a window of a single row, index the row first and then slice it, as in grid[r][1..<3].
A named rectangle of mutable or mapped memory also names its parent cells. Indexes count from the selected corner, and rows retain the parent's spacing:
var grid: [3 of [4 of Number<u8>]] = 0
panel <- grid[1..<3, 1..<3]
when start
panel = [[1, 2], [3, 4]]
panel[1][0] = 9
end
System.screen.border <- Color(grid[2][1])panel[1][0] is grid[2][1]. Index two is outside either dimension of this two-by-two panel even though the parent has more cells. Overlapping window and rectangle assignments capture the whole source before writing.
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
var top: Number<0...1> = 0
corner <- grid[top..<(top + 2), 1..<3] // two rows of two numbers
when System.keyboard.space.pressed
top = top +% 1
end
System.screen.border <- Color(corner[1][1])Joining Lists
The ++ operator joins two lists end to end: a ++ b contains all the elements of a followed immediately by all the elements of b. Both lists must share the same element type (or both be lists of numbers), and their combined length can be up to 65,535 elements. To keep memory layout simple and predictable, each side of ++ must be a list literal, a named list, a struct member, or an indexed element; if you try to join the result of a function call directly, the compiler flags joinLists—just bind that call to a name on the line above first. The free helper append(left, right) also joins fixed lists and accepts computed list expressions directly. Drawing lists have their own composition rules, described under Drawings.
const low = [1, 2, 3]
var high: [2 of Number<u8>] = [7, 8]
all_of <- low ++ high // [5 of Number<u8>]
System.screen.border <- Color(all_of[4] % 16)Joining Texts
++ also joins Text values into one line: Text("SCORE ") ++ Text(score.digits(4)).ink(.yellow) shows SCORE followed by the four digits, and each part can take its own .ink(...). The joined line is placed as a whole, as in (Text("SCORE ") ++ Text(score.digits(4))).at(row: 0, col: 2). See Text Placement for the words that place and style a text.
Value if and match
Use if and match inside an expression to pick a value. They also run statements in handlers. Only the branch or arm that wins is worked out; the others are skipped.
if
Because an expression must always produce a value, a value if always needs an else branch; leaving else off triggers valueIfElse. The condition after if can be any bool expression, or an event (which counts as true during any frame in which that event fires). You can chain additional tests with else if on the same line, closing the whole chain with a single end.
Each branch can be a compact one-liner or span several lines: when a branch spans multiple lines, you can define local helper constants with const on the opening lines, and the final line of the branch becomes its resulting value. Inside the then branch, Adder knows the condition is true and narrows your number ranges accordingly—so in if a > 3 then a - 4 else 0 end, the compiler knows a is at least 4 in the first branch and proves that a - 4 never drops below 0.
All branches of a value if must agree on the type of value they return (mixing types raises wrongType). When the branches return numbers, the overall range of the if expression spans from the lowest minimum of any branch to the highest maximum of any branch.
var a: Number<0...9> = 0
lift <- if a > 3 then a - 4 else 0 end // 0 to 5
shade <- if a == 0 then Color.red else if a < 5 then .yellow else .green end
scaled <- if a > 5 then
const over = a - 5
over * 3
else
0
end
when System.keyboard.space.pressed
a = a +% 1
end
System.screen.border <- shade
System.screen.text[0][0..<2] <- (lift + scaled).digits(2)match on a Value
When you are choosing between several cases—like game states, directions, or specific numbers—match value inspects the value from top to bottom, picks the first arm whose pattern matches, and returns the expression after ->.
| Value | Patterns |
|---|---|
| an enum | a case name without a dot, such as title; a case with fields names them, as in moving(grab, column: chosen) |
| a named set | a value's name without a dot, such as red |
| a number | a whole literal, such as 0 or -3 |
a Char | a quoted character, such as "#" |
a bool | true and false |
| an optional | nil, and the patterns of its inner type |
| any value | a name, which matches any value and names it inside the arm |
You can refine any pattern by adding when condition before the ->; that arm then matches only when both the pattern and the condition hold, and the compiler narrows the range of any matched name by that condition! An else -> arm at the bottom catches everything that earlier arms did not take.
Adder makes sure your match is watertight:
- Every possible value of the input must be handled by some arm; if any case or number is left out, the compiler lets you know with
missingCoverage. - If an earlier arm without a
whenguard already catches a value, a later arm for the same value could never be reached, so the compiler flags it withduplicateArm. - Case patterns in a
matcharm are written cleanly without a leading dot (title ->, not.title ->); writing a dot triggersdottedArm.
enum Mode
case title, playing, over
end
var mode: Mode = .title
var lives: Number<0...3> = 3
System.screen.border <- match mode
title -> .blue
playing -> .black
over -> .red
end
System.screen.background <- match lives
0 -> .red
n when n < 3 -> Color(n + 7)
else -> .black
end
when System.joystick[2].fire.pressed
mode = mode.next()
lives = lives -| 1
endmatch Without a Value
Write match with nothing after the keyword to choose between a series of conditions. Each arm starts with when followed by a bool expression or an event. Adder checks the arms from top to bottom, picks the first one that holds, and skips working out the rest. A condition-table match must have at least one when arm and finish with an else -> fallback; leaving either out triggers conditionalMatch.
var lives: Number<0...3> = 3
System.screen.border <- match
when lives == 0 -> Color.gray
when System.joystick[2].fire -> Color.red
else -> Color.black
endCalls and Members
Calls
To call a function or an op, write its name followed by its arguments in parentheses: apart(ball, bat). Adder acquires the receiver or callable once, then works out explicit arguments from left to right before running the function. Each argument's type and range check finishes before the next argument starts; a failing argument prevents the call and any later arguments. You can pass arguments by position, or attach the parameter's name as a label—like apart(ball, b: bat)—and labeled arguments can appear in whatever order reads best. Each argument is checked against the parameter's declared type and range just as if you were storing it into a variable.
If a call does not line up with the declaration, the compiler tells you right away:
badArgumentwhen a label does not match any parameter name, when the same parameter is supplied twice, or when too many arguments are passed;missingArgumentwhen a required parameter is left out;unknownFunctionwhen the function has not been declared above the call.
fn apart(a: Number<0...296>, b: Number<0...296>): Number<0...296>
if a > b then a - b else b - a end
end
var ball: Number<0...296> = 40
var bat: Number<0...296> = 100
gap <- apart(ball, b: bat)
System.screen.border <- if gap < 16 then .green else .black endDeclarations shows how to write your own functions and ops.
Pipes
Read a series of calculations from left to right with |> or :>. The two spellings mean exactly the same thing; :> uses keys available on a Commodore keyboard. You can mix them in one chain.
type Digit = Number<0...15>
fn flip(value: Digit): Digit
15 - value
end
fn step(value: Digit, extra: Digit): Digit
value +% extra
end
var input: Digit = 3
result <- input |> flip :> step(extra: 2)
System.screen.border <- Color(result)value |> transform(extra) passes value as the first argument and extra as the next one. A bare name, value |> transform, supplies just the first argument. A member keeps its explicit receiver: value |> item.transform(extra) passes value as that method's first explicit argument.
The input is captured once before the receiver or callable is acquired. Its first-parameter check finishes before later arguments run. Each call and result check finishes before the next stage begins; missing optional values are passed on as values. An earlier failure blocks all later work and publication.
Pipes keep ordinary call rules. A named declaration may use labels and existing list lifting; a function value takes positional arguments with exact shapes. value |> choose(flag) calls choose(value, flag). To first obtain a function from choose(flag) and then apply it, write value |> (choose(flag)).
Arithmetic and Boolean operators bind before pipes: a + b |> flip pipes the sum. Chains associate to the left, and trailing when applies after the whole chain. For a multiline chain, begin each following stage with its pipe token. Comments and blank lines may separate those stages.
Callable Values
A function value can be called wherever an expression produces it: transform(3), (flip)(3), callbacks[index](3), strategy.apply(3) for a callable field, or choose(flag)(3). Its signature supplies positional parameters, so an alias uses transform(3) rather than transform(value: 3). A directly named declaration keeps its optional labels, such as flip(value: 3). The selected callback is acquired once before any argument work, even when a later argument changes the place it came from. The callback's declared result is checked before its caller stores or shows that result.
Calls through values require the signature's complete argument shapes. A scalar callback does not automatically traverse a list: use map(digits, transform). A signature such as fn([4 of Digit]): Digit instead takes the whole four-element list once. Directly named declaration calls retain their ordinary list lifting.
type Digit = Number<0...9>
fn flip(value: Digit): Digit
9 - value
end
const transform: fn(Digit): Digit = flip
const digits: [3 of Digit] = [1, 3, 7]
lifted <- flip(digits)
mapped <- digits |> map(transform)
System.screen.border <- Color(lifted[0])
System.screen.background <- Color(mapped[0])A function expression creates a pure callable with one value expression as its body. Write fn(value: Digit): Digit -> 9 - value; omit parameter or result annotations only when the surrounding signature or checked body determines concrete types. Payload events retain their local item -> expression shorthand. Fixed-list callbacks use named functions or explicit fn expressions.
Functions as Values shows complete helpers, returned callbacks and local snapshots.
Members
A dot . after a value reaches for one of its members. Plain struct fields and properties need no parentheses (position.x, pool.count), while member functions that compute something take parentheses (score.digits(3)). When you declare a member function like fn Type.name(value: Type, ...), calling item.name(...) passes item (the value before the dot) into that first parameter automatically.
When the compiler already knows what type a place expects—for instance, assigning to System.screen.border or comparing against a Color—you can start with a bare dot like .red instead of spelling out Color.red. If you write .name in a spot where no specific type is expected yet, the compiler asks you to name the type with memberNeedsType. When a name before the dot begins with a capital letter, it refers to a type itself, giving you access to its cases (Color.red), its range bounds (Destination.first and Destination.last), and its type-level makers like Color.random() and Number.random(0...15).
struct Position(x: Number<u8>, y: Number<u8>)
fn Position.is_left(value: Position): bool
value.x < 20
end
var position: Position = (x: 10, y: 12)
left <- position.is_left()
System.screen.border <- if left then .white else Color.black endAsking a struct for a field it does not have raises unknownField, and asking a type or value for a member that does not exist raises noMember or unknownName.
Operations Over Lists
Lifted Operations
Pass a list to an arithmetic or comparison operator to apply the operation to every element in turn and get a fresh list of results. You can combine a list with a single value (which pairs with every element in the list) or combine two lists of the same length (which pair up slot by slot). The two exceptions are == and != between two lists, which compare them as whole values (Comparisons explains), and the ordering comparisons, which still pair up slot by slot. Trying to combine two lists of different lengths raises arrayShapes.
When a directly named function or op expects one value for a parameter, you can pass a list to run it on every element. For an op, each slot keeps its own independent memory from frame to frame. (If a parameter is explicitly declared to take a list, the function receives the whole list at once instead.)
const xs = [1, 2, 3]
const ys = [4, 5, 6]
fn half(x: Number<0...9>): Number<0...4>
x / 2
end
sums <- xs + ys // [5, 7, 9]
scaled <- xs * 2 // [2, 4, 6]
big <- ys > 4 // [false, true, true]
halves <- half(ys) // [2, 2, 3]
System.screen.border <- Color(sums[0] + scaled[1] + halves[2])
System.screen.background <- if big[2] then .green else .black endReductions
When you want to boil an entire list down to a single summary value—like adding up column heights or checking whether any alien has reached the bottom row—use a reduction:
| Reduction | On | Result |
|---|---|---|
sum(xs) | numbers, possibly optional | the sum of present values; zero when all are absent |
min(xs) and max(xs) | numbers, possibly optional | the smallest/largest present value; nil for an all-absent optional list |
count(xs) | any fixed list | the number of present slots, including present false values |
any(xs) and all(xs) | Boolean values, possibly optional | whether any/every present value is true; all-absent identities are false/true |
first_index(xs) and last_index(xs) | Boolean values, possibly optional | the physical index of the first/last present true, or nil |
List reductions work purely on the current contents of the list—they keep no memory between frames—and their cycle cost scales with the number of elements in the list.
var drops: [6 of Number<0...999>] = [60, 200, 120, 300, 90, 250]
deep <- drops |> filter(fn(n) -> n > 160) |> count
all_drops <- sum(drops)
first_deep <- first_index(drops > 160)
when System.keyboard.space.pressed
drops[0] = 400
end
System.screen.border <- if any(drops > 350) then .red else Color(deep) end
System.screen.text[0][0..<4] <- all_drops.digits(4)
System.screen.text[1][0..<1] <- (first_deep ?? 0).digits(1)map and filter
map(values, transform) calls a pure function for each present value and keeps its result in the same slot. filter(values, predicate) keeps a value when its predicate returns true, leaving nil in rejected slots. Both preserve the fixed capacity and skip slots already absent. Optional results stay flat (T?). Filtering three slots still gives three slots, with visible gaps where values were rejected. Use count to ask how many are present.
The source supplies the callback's present input type. Use a named function or an explicit fn expression; filter requires a Boolean result. Each complete stage finishes before the next begins, including all of its checks.
type Digit = Number<0...9>
fn high(value: Digit): bool
value >= 3
end
const values: [3 of Digit?] = [2, nil, 4]
kept <- values |> filter(high) :> map(fn(value) -> 9 - value)
System.screen.border <- Color(kept[2] ?? 0)Adder captures the source and then the callback once, even for an all-nil list. It visits present slots in increasing index order and replaces a destination only after the complete result succeeds. Pure callbacks can still fail checks; their failure order is part of the program.
A map over constant slots can write straight into a fixed list, including a sprite formation, at the cost of writing out those results. Adder keeps a temporary whenever snapshots or checks need it.
An explicit fn callback follows pure-function capture rules, including local snapshots. Sample changing values in the caller and capture read-only locals when a transform needs them. Value-carrying events retain the local item -> expression form; typed callable event callbacks are not supported. Event map, filter, and sum(from:) are described in Events and Handlers.
Combining and searching fixed lists
Collection helpers take their source first, so direct calls and pipes compose the same way. Their names are ordinary names: an authored binding or declaration shadows the standard helper. A mismatching authored call reports its own error.
| Helper | Result and callback |
|---|---|
indexed_map(xs, transform) | Same capacity; fn(index, value) receives the original zero-based index and each present value. |
zip_with(xs, ys, combine) | Equal capacities; combines matching present slots, leaving a hole if either input is absent. |
append(xs, ys) | All physical slots of xs followed by all physical slots of ys. Both arguments may be list expressions. |
reverse(xs) | Reverses physical slots, including holes. |
find(xs, predicate) | First present match, or nil; stops calling the predicate after a match. |
find_index(xs, predicate) | Original index of that match, or nil. |
contains(xs, value) | Whether a present slot equals value, using ordinary scalar equality. |
first(xs), last(xs) | Physical endpoints, including endpoint absence. |
moved_to_end(xs, value) | Moves the first slot equal to value to the end, preserving the others' order; a missing value leaves the list unchanged. |
flatten(rows) | Row-major rectangular slots; an absent row contributes a whole row of holes. |
flat_map(xs, transform) | Completes a map to fixed-length rows, then flattens them. All callback results have the same row capacity. |
flatten and flat_map have a capacity fixed by the row sizes. They do not compact missing values or grow a list at runtime. Joined/product capacities must fit 65,535 slots and the program's ordinary memory and frame budgets.
Helpers over a list that grows
A list that grows, [up to N of T], has no empty places, so these helpers see its live items only, in order, and a helper that gives a list gives a list that grows with the same capacity. Its items are plain: a list that grows of optionals is not read by them.
| Helper | Result |
|---|---|
map(xs, transform) | The results for each live item, as a list that grows of the same length. |
indexed_map(xs, transform) | The same, with fn(index, value) receiving each item's zero-based position. |
filter(xs, predicate) | Only the items that pass, in order, closing the gaps; the length is the number kept. |
zip_with(xs, ys, combine) | Combines matching items. The two lists must have the same length, or the program stops; the capacity of the result is the smaller of the two. |
reduce(xs, initial, combine), scan(xs, initial, combine) | The total, and the list of running totals as long as xs. An empty list gives initial, and an empty scan. |
count(xs), sum(xs) | The length, and the total of the items (0 when empty). |
min(xs), max(xs) | The least or greatest item, or nil when the list is empty. |
any(xs), all(xs) | For a list of bool: whether one or every item is true. An empty list gives false and true. |
find(xs, predicate), find_index(xs, predicate) | The first item that passes, and its position, or nil; the predicate is not called again after a match. |
first(xs), last(xs) | The first or last live item, or nil when the list is empty. |
contains(xs, value) | Whether a live item equals value. |
The callbacks are pure functions and inline fn expressions, as for the helpers above. A callback that receives a String reads the line where it sits, so a helper over long lines costs a look at the line a turn and no copy of it (a filter copies each kept line once, into its result): plan a frame for the lines a helper walks, or walk a few each frame. append, reverse, flatten, flat_map, first_index, last_index and moved_to_end are not helpers of a list that grows. Fields, projections, indexing and slicing remain available. Numeric, String, Font, storage, geometry, presentation and event operations keep their own members. A standard collection function can itself be a pure function value when context supplies its complete concrete signature, including capacities.
reduce and scan
reduce(xs, initial: seed, combine: callback) walks left to right with one accumulator. Its callback takes (accumulator, value) and returns the same accumulator type. Missing input slots do not call the callback; an all-nil list returns the seed. An optional accumulator is real state: a nil accumulator is passed to the next present callback rather than skipping that callback.
scan uses the same seed and callback but returns one accumulator after each physical input slot. It returns N values for N slots; the seed is internal. A missing input repeats the previous accumulator in that output slot.
type Total = Number<-100...100>
fn subtract(total: Total, value: Number<0...9>): Total
total - value
end
const readings: [3 of Number<0...9>?] = [2, nil, 4]
const seed: Total = 10
total <- readings |> reduce(initial: seed, combine: subtract) // 4
steps <- readings |> scan(initial: seed, combine: subtract) // [8, 8, 4]
System.screen.border <- Color(total)
System.screen.background <- Color(steps[1])Each callback result is checked before the next step begins. A failed step prevents later callbacks and complete-result publication. The seed, source and callback expressions are still acquired once when no input is present.
Random Numbers
Games thrive on a little surprise! Number.random(range) draws a whole number from a range whose start and end are known at compile time (passed directly without an argument label), and Color.random() picks one of the sixteen colors.
roll <- Number.random(1...6)
const low = 2
sample <- Number.random(low..<(low + 8))
var shade: Color = .black
when System.keyboard.space.pressed
shade = Color.random()
end
System.screen.background <- shade
System.screen.border <- Color(roll + sample)Every random call site in your program has its own independent number generator under the hood, so adding a random starfield in one part of your code will never shift the dice rolls in another part. A call draws a fresh number only in the frames where its line actually runs—so a random call inside a when handler advances only when that handler fires. If you want one random roll to be shared by several places in the same frame, put the random call in a binding (roll <- Number.random(1...6)) and read roll wherever you need it. Restarting the program replays the exact same sequences from the beginning, making tricky bugs easy to reproduce.
Adder draws from ranges of any size, including sizes that are not powers of two, without a division instruction. Because the generator is tailored to the range at compile time, a range with changing endpoints is flagged with rangeEndNotFixed, and passing anything other than a range to Number.random triggers randomNeedsRange. Finally, because a plain fn promises to return the exact same answer every time you give it the same arguments, calling random inside a fn is caught with randomImpure.
Declarations
Every game or demo you build is made of things you name: a ship's horizontal position, the number of lives left, a melody table, a helper formula for checking collisions, or the live rule that paints the screen border. In Adder, a declaration introduces a name and makes a clear promise about when—and how—its value can change:
- A constant declaration, written as
const name = expression, fixes a value at compile time at the program or case level. A localconstcaptures its expression once when that line runs, and keeps that value even if the variable it read changes later; when that can happen the compiler holds a copy, and the cost report shows it on theconstline. A barename = expressionassigns to existingvarstate. - A variable, written with
var, holds state from frame to frame and changes only when an event handler assigns it a new value. - A binding, written with
<-, is a live wire: it always equals its expression, updating automatically as the values it reads change. - Functions (
fn), ops (op), and work (work) give names to calculations, while types (type,enum,struct) give names to kinds of values. atplaces a value at a specific spot in memory, andincludebrings another source file into your project.
Declarations stand at the top level of your program, one per line, or inside a case as Events and Handlers explains. You can arrange your declarations and handlers in whatever order tells the story of your program best, with one simple rule: declare a name above the first line that reads it.
Names and Scope
Every declared name follows the spelling rules in Names. Type names always start with a capital letter (Ship, Score), while constants, variables, bindings, functions, and ops always start with a small letter or an underscore (lives, ship_x). Starting a non-type declaration with a capital letter triggers capitalizedDeclaration.
Once you declare a name, it is in scope from that line all the way to the bottom of the program. Any line that reads a name or calls a function must appear after its declaration; reading a name too early raises unknownName (or unknownFunction for a call). There is just one special exception: a binding can look back at the previous frame's value of a binding written further down the page, as A Binding That Reads Itself shows.
Each name in your program—across all included files—is declared only once. Declaring the same top-level name a second time raises duplicateDeclaration, and reusing a top-level name for a parameter or local variable inside a block raises shadowing so you never lose track of which value you are looking at.
Built-in type names, System, and scratch are reserved for the machine and cannot be redeclared (builtinName). Built-in member names like digits and sum, however, are completely free for you to use as variable or function names of your own.
The compiler checks every single declaration in your file, even if nothing calls or reads it yet. An unused function or struct member is checked for undeclared names, missing types, or misplaced statements (like a wait outside a handler) just as thoroughly as one you call every frame. Generic functions with type parameters are checked up front for their names, types, and statement placement, and then checked for exact number ranges at each call site. The compiler removes unused declarations, so they cost zero bytes in your final binary.
Constants
Write const name = expression to declare a constant whose value is locked in when the program compiles. For number constants, the compiler bakes the number straight into the machine instructions that use it, so the constant does not even take up a byte of storage in memory.
A constant's expression can combine literals, earlier constants, pure functions, and type makers like Color.red, ScreenCode("ADDER"), or Shape([...]). You can also put a constant list, struct, or picture in a constant, or give a short nickname to a branch of the hardware tree—like screen = System.screen—and use screen as a stand-in for that path.
const columns = 40
const half = columns / 2
const table = [3, 1, 4]
const screen = System.screen
var lane: Number<0...39> = half
screen.border <- Color(table[1] + lane % 8)When you leave off the : type annotation, the constant takes the exact value and tightest range of its expression. When you write a : type annotation, the compiler verifies at compile time that the constant fits inside that type, flagging literalDoesNotFit if it steps outside.
Because a constant is worked out before the program ever starts, it cannot read anything that changes while the program runs—no variables, bindings, live device inputs, or ops (constantChanges). And once declared, a constant stays constant forever: trying to assign a new value to one in a handler raises notAssignable. Constants cannot hold events either, as Events explains.
These compile-time rules apply to ordinary program-level and case-level constants. A local const inside a function or handler may read its current inputs and state; it keeps that captured value for the rest of the block, as Statements explains. Special declarations such as Publications use const to name a service and follow that service's initialization rules.
A pure function called by a compile-time constant may use local variables and bounded loops to build a table. Its finished result becomes fixed program data; a function used only for that calculation needs no runtime body. Prefer this to maintaining a generated table as changing state.
Compile-Time Assertions
A value can fit its type while breaking a relationship your program needs. In Cargo drop, the falling pod stops at Y = 179.0; the clamp must be reachable before then:
const clamp_y = 170
const pod_limit_y = 179.0
#assert clamp_y <= pod_limit_y, "The pod must be able to reach the clamp."
var pod_y: Number<0.0...pod_limit_y> = 0The assertion succeeds at 170 and at 179. Changing the clamp to 180 refuses compilation with your explanation. A successful assertion adds no instructions, message text, storage or frame work to the C64 program.
Place assertions at unconditional top level, after any constants they read. Included source files can assert their own relationships, and their assertions are checked even if their declarations are unused. Unreferenced project files are not checked merely because they exist. Source-library builds check assertions before producing a fixed-placement library or .addl file; importing an already compiled library needs no assertion evaluator or source. Assertions inside functions, handlers, outputs, work bodies or declaration cases are refused.
The condition must be a fixed bool. It may use numeric and Boolean literals, earlier resolved Number or bool constants, parentheses, unary - and not, ordinary + - * / %, compatible comparisons, and and/or. Number aliases, ranges and formats retain their ordinary meaning. Calls, members, indexing, hardware or enum constants, variables, bindings and device readings are outside this initial set of expressions. Even true or live_flag is refused when live_flag changes.
Assertions use the existing checked constant arithmetic. Every operand is checked: true or (1 / 0 == 0) still reports division by zero. Conditions are limited to 128 expression nodes and depth 32, alongside the usual parser nesting limit. The explanation is required and must be one printable ASCII string literal, without interpolation, on the same physical line. Ordinary quote and backslash escapes and trailing comments remain available. Invalid expressions keep their own diagnostic; a valid false condition reports an assertion failure at its source.
Variables
Write var name = expression to declare a variable—a slot in memory that remembers its value from one frame to the next, like the player's score, remaining lives, or current game mode. The expression after = sets the variable's starting value when the program boots up, or whenever its declaring case starts. An event handler changes it directly with =, through a mut parameter, or with a mut fn member.
Every var declaration must include a starting value (= expression). Because the program works out that starting value as it starts up, the starting expression can read constants, earlier variables, bindings, functions, and even live hardware inputs like the joystick!
enum Mode
case title, playing
end
var lives: Number<0...3> = 3
var mode = Mode.title
var start_x: Number<-1...1> = System.joystick[2].dx
when System.joystick[2].fire.pressed
lives = lives -| 1
end
System.screen.border <- Color(lives + start_x + 1)If you omit the : type annotation on a var, it takes the type of its starting expression—and for a number, it widens to The Default Number (-32,768...32,767) unless you give it a range like Number<0...3>. If the starting value is a bare dot-name like .red, add a type annotation (var shade: Color = .red) or write Color.red so the compiler knows which set the case belongs to (memberNeedsType).
Each top-level variable occupies just the bytes needed by its type. Handlers and functions can also declare temporary local var values that live only while that block runs, as Statements describes.
Bindings
Write name <- expression to declare a binding. An unqualified pure binding follows its expression's current inputs. Whenever a variable or input it reads changes, reading the binding gives the new answer. Temporal members and execution clocks instead retain their answers between their clock's occurrences. A computed binding is defined by its formula, so assigning to it is refused (notAssignable). A binding of a memory window instead names the selected backing places and permits the same writes as those places.
var lives: Number<0...3> = 3
warning <- lives == 1
spare: Number<0...2> <- lives -| 1
System.screen.border <- if warning then .red else .black end
System.screen.text[0][0..<1] <- spare.digits(1)
when System.keyboard.space.pressed
lives = lives -| 1
endWithout a : type annotation, a binding takes the exact type and range that the compiler proves for its expression. With a : type annotation, the binding takes that declared type (and checks the value at runtime if the compiler cannot prove the expression already fits). For a memory window, the annotation must match the selected places exactly; it cannot convert them to another type. A binding can also give a name to an event—for instance, jump <- System.joystick[2].fire.pressed—so that when jump handlers can listen to it; see Events.
Use a binding for an answer determined entirely by current state, such as warning <- lives == 1. Store a var when the program needs to remember something independent, such as the lives remaining or the last submitted message. Keeping a second variable synchronized with a calculation creates extra assignments to maintain.
Putting the keyword fast in front of a binding asks the compiler to spend extra bytes of memory or lookup tables to save CPU cycles on that line, as Costs and the Frame explains.
Mapped list windows use the same syntax. This three-cell field names part of hud, and the second <- maintains those cells:
hud: [4 of [10 of ScreenCode]] at 0xC000
field <- hud[2][3..<6]
var speed: Number<0...99> = 12
field <- speed.digits(3)
when System.keyboard.space.pressed
speed = speed +% 1
endThe digits go to row two, columns three through five of the mapped memory. Reading field reads those cells; var saved = field would capture a separate copy at initialization.
An active unqualified output binding updates its cells after handlers. If a handler overwrites one of its mapped cells, the binding restores its final value, even when that value stayed the same. A case's output maintains its cells only while that case is active.
Calculations in a Binding Body
Put a newline after <- when a calculation needs local names or a bounded loop. The binding's own end closes the body, and the last expression gives its value. An if or match on that last line gives a value from each arm; its own end comes before the binding's end.
var charge: Number<0...3> = 1
brightness: Number<0...9> <-
var total: Number<0...9> = 0
for i in 0..<3
total = total +| charge
end
total
end
System.screen.border <-
const lit = brightness > 0
if lit then .green else .black end
end
when System.keyboard.space.pressed
charge = charge +% 1
endEach evaluation starts its locals afresh. Here total begins at zero each time the current charge is used; it does not remember an earlier answer. Local const and var names stay inside their body. A body without memory follows the same current-read rule as an expression binding, so a handler can change charge and then read the new brightness on its next line.
The annotation or output destination supplies the final value's expected type, including every final if or match arm. In the output above, .green and .black are colors because the destination is the screen border. A declaration, assignment or loop cannot be the body's final answer.
A body can change its own local variables, including through ordinary mut calls. It cannot assign outer state or registers, print, call Publication.publish, run an action, submit work, use assembly, wait or declare a handler. Keep those effects in their existing handlers and services. A body creates no function or job; use a named fn when the calculation belongs in several places.
Temporal members still own memory at their written calls. Any body-local source they retain must be available unconditionally on the binding's tick; putting memory inside a branch or loop does not create a varying number of instances. A previous of a local retains that local's value when the body finishes. Like other bindings, it captures that value before handlers run. Reading the held answer does not advance it. See Remembering With previous and Events and Handlers for the existing clock rules.
Only a physical newline after the arrow opens this body. A comment after the arrow is allowed. An expression that starts on the arrow's line keeps its usual bracket and pipe continuations and needs no additional end.
Binding Execution Clocks
Put on clock before <- to choose when a binding evaluates and commits its answer. An annotation or mapped at address comes before on. The qualifier applies to either an expression or a body:
var level: Number<0...15> = 0
pulse <- System.screen.frame.every(8)
when System.screen.frame
level = level +% 1
end
System.screen.border on pulse <-
const shifted = (level + 1) % 16
Color(shifted)
end
System.screen.background on System.screen.frame <- .blackThe border calculation runs on pulse; its color stays held between those occurrences. Reading a qualified value does not run it again. A named upstream producer keeps its own clock, even when a less frequent consumer reads it. An ordinary qualified value has no answer before its first successful activation. The compiler refuses a read whose producer is not yet available and identifies the producer and consumer. Use an initialized sampler when an answer is needed before the first capture.
Evaluation and result checks finish before the binding commits its new value or output. A failed result does not write that binding's outputs; earlier completed work keeps its effects. A constant scheduled output still performs its required service. Several device registers do not become one atomic hardware update.
on clock schedules a binding. The on: argument narrows an operation's own occurrences, while sampled(on: clock, from: initial) captures another producer's answer without changing that producer's history. A newly qualified binding's temporal instances initialize on that binding's first activation. An unqualified op(on:) still initializes in the first foreground frame. If a binding's whole answer is a sampler, an explicit outer qualifier must agree with the sampler's clock; write a second sampler for a second crossing.
Fixed Raster Capture and Outputs
A fixed native clock evaluates a supported binding at a fixed picture row. It is a service designator in that clock position, not an ordinary event to store or combine with foreground events. The first capture form uses a constant ordinary value or Publication.current, with fixed forward readers in the same display period:
const initial: [2 of Number<u8>] = [23, 27]
const state = Publication(initial: initial)
shown <- state.current.sampled(
on: System.screen.interrupt(line: 20),
from: initial
)
when System.keyboard.space.pressed
state.publish([29, 31])
end
System.screen.border on System.screen.interrupt(line: 30) <- Color(shown[0] % 16)
System.screen.background on System.screen.interrupt(line: 40) <- Color(shown[1] % 16)The sampler acquires one complete generation at line 71. Both later services use that generation, even if the foreground commits a replacement between them. from: supplies a checked initial value before services are enabled; the first line-71 service still captures immediately. Publication remains the explicit foreground commit service. See Publications for complete-value replacement and acquisition.
The compiler checks every direct and indirect reader, the last use before storage reuse, exclusive device access and the complete service costs. The first native form refuses foreground reads of this captured value, case-local native instances, changing raster positions, consumers before the capture or across the next period, and timer or otherwise unproved clock crossings. Passing an ordinary value through a helper does not bypass those checks.
Scalar device services such as the border and background writes above keep their own value and resource rules. Several fixed services can share a physical resource only under one checked schedule; an uncoordinated foreground writer conflicts with it. A constant scheduled write still runs at its chosen line. Complete data capture does not make several register writes atomic or prepare memory referenced by a device value. This does not select sprite slots, admit a changing sprite reuse schedule or promise a presentation transaction for every device.
Outputs
When the left side of <- is a hardware or memory place rather than a fresh variable name, the binding is an output: System.screen.border <- expression keeps the screen's border color wired to that expression every frame. An output target can be any writable spot in the hardware tree—the border, the background, a row or cell of screen text, a sprite, a voice—or a memory location declared with at. The System Device Tree tours all the built-in output places and the types they accept.
Each unqualified output place is driven by a single binding in your program (or within a case). Wiring two such bindings to the same output place triggers overlap.
Foreground handlers cannot assign computed bindings or device output bindings directly (notAssignable). To control a device output from a foreground handler, update a var and wire the output to it with <-. Mapped list cells remain writable, directly or through backed windows; an active unqualified output restores its final value after handlers.
A Binding That Reads Itself
Within a single frame, a binding has no value until its expression finishes running—so a binding cannot read its own current-frame value, nor can two bindings read each other in a circle (bindingLoop).
What a binding can do is read what its value was in the previous frame using .previous(from: initial). The from: argument supplies the starting value for the very first frame before there is a previous frame to look back at:
tick: Number<0...99> <- tick.previous(from: 0) +% 1
System.screen.border <- Color(tick % 16).previous(from: ...) can even read a binding that is declared further down the page, letting two bindings feed into each other across frames! When a binding reads a later binding through previous, that later binding must write out its : type annotation so the compiler knows its size up front (forwardNeedsType).
Order in a Frame
Every television frame follows a clean, predictable rhythm:
- First, the program samples the hardware inputs (keyboard, joysticks, paddles) and works out which events fired this frame.
- Next, the
whenhandlers whose events fired run from top to bottom in the order they are written. - Finally, once all handlers have finished, every unqualified output binding updates the screen and sound hardware with the final value of its expression. Explicitly clocked bindings evaluate and commit on their admitted clock instead.
Inside a handler, any assignment to a var takes effect right away on the next line. Reading an unqualified pure binding gives the answer from those current variables.
var n: Number<0...4> = 1
doubled <- n * 2
var seen: Number<0...8> = 0
when System.screen.frame
n = 3
seen = doubled
end
System.screen.border <- Color(seen)In this example, seen becomes 6 on the very first frame: the handler sets n to 3, and reading doubled on the next line uses that new 3 right away.
What about a binding that remembers history across frames—one that uses .previous(), an op, or a stateful member like .sum() or .count()? Those sources advance on their own clock, respecting any on: and reset: events. Reading a stateful binding again does not advance its memory or take another sample. Events and Handlers walks through the frame cycle in complete detail.
Output Declarations
If you find yourself wiring the same group of hardware outputs together—say, setting both the border and background colors from one mood color, or configuring a sprite pair—you can bundle them into a reusable output declaration:
output frame_color(c: Color)
System.screen.border <- c
System.screen.background <- c
end
var hue: Number<0...15> = 0
frame_color <- Color(hue)
when System.keyboard.space.pressed
hue = hue +% 1
endWhen you wire frame_color <- Color(hue), the parameter c receives Color(hue) and drives every output binding inside the block. An output block may contain output bindings (including bindings to other declared outputs) and asm blocks; putting any other kind of line inside triggers outputBody, and using <- on a name that is not an output triggers outputTarget. Just like a built-in hardware output, your custom output takes a single <- binding and cannot be assigned with = inside a handler.
Functions
A function (fn) is a named, self-contained calculation. Give it the same argument values and it will give you back the exact same answer every time, with no hidden state or surprises.
fn apart(a: Number<0...296>, b: Number<0...296>): Number<u16>
if a > b then a - b else b - a end
end
bat: Number<0...296> <- (System.joystick[2].dx * 4).sum(from: 136)
ball: Number<0...296> <- System.screen.frame.cycle()
close <- apart(ball, b: bat) < 16
System.screen.border <- if close then .green else .black endCallable Byte Exports
Callable libraries are a work in progress.
export fn exposes one total byte calculation to an application importing its compiled library or to an independent assembly caller. Declare one or two Number<u8> value parameters and a Number<u8> result. The calculation must return safely for every byte input. Ordinary source calls keep the same arithmetic and evaluation rules.
export fn add_one(n: Number<u8>): Number<u8>
n +% 1
end
export fn add_two(a: Number<u8>, b: Number<u8>): Number<u8>
a +% b
endHere +% wraps, so 255 plus one is zero. Checked n + 1 can fail and is refused for an export. The compiler checks reachable helpers, ranges and effects conservatively. Local variables and bounded loops are allowed when every path is total. Device and temporal work, mutable globals, captures, recursion, callbacks, assembly and unsupported signatures are refused at their source. A pure function can still fail, so purity alone does not qualify an export.
Library sources contain types, constants and functions. Build a compiled library with adder compile --library math.adder --name math --library-version 1.0.0 -o math.addl. An application imports that file and calls its public functions; the compiler chooses addresses and initializes the library. The separate fixed-placement build provides addresses, bindings and costs for an independent assembly caller. Source names beginning with adder_ and names that collide with public bindings are reserved for exports.
Imported functions execute on the C64; their compiled bodies are not evaluated as compile-time constants. Use a var initializer to call one once at startup, as the Compiled math example does, or call it from a handler when needed. Imported functions support direct calls rather than callback values and cannot run in an interrupt handler.
Mutable Parameters
A parameter marked mut changes the caller's place during one function call. The call also writes mut: raise(mut wins, depth). A var, a field, element or slice of one, a local variable, or a calling function's own changing parameter can be passed this way. Its type must match exactly. An ordinary fn changes caller values only through these parameters; a member can also declare mut fn to change its receiver.
Each argument path is checked and fixed once in written order. Two changing arguments, and a changing receiver, must be different places: different variables or fields, differing fixed indices, or disjoint ranges. Inside if i != j then, swap(mut cells[i], mut cells[j]) is allowed. Ordinary overlapping arguments keep their values from before the body starts. A returned value, including a slice, is a copy. There are no variables holding changing places. Bindings cannot make these calls. A work body may pass its own local var to a helper between turns; work and op parameters cannot take mut.
The Lab's source hover and cost summary describe the places a call may change, including writes through nested calls. The 6502 cost inspector exposes the exact fields and ranges, with expanded helper calls available separately. The call charges its path checks, address setup, body and change marks without copying or comparing the changing value.
String<N> is an ordinary mutable place, including a field or list element. A helper can assign s = s ++ "!", call s.append("!") or s.insert("!", at: 0), or replace it with s = "ok"; successful writes update its live length and characters together. The capacity boundary still checks before replacing the value.
A helper can take both changing places and pure callbacks, such as apply_in_place(mut items, transform). The helper changes the places; the callback keeps its pure signature. A function with mut parameters cannot itself fill a pure callback slot, even if it also returns a value. Checked interrupts may use such helpers on invocation locals when every possible callback target is interrupt-safe.
Parameters and Results
The head of a fn (or an op) declares its parameters inside the parentheses, and each call to it supplies the argument values for that run. Ordinary parameters are read-only input names written without var: each call hands them their value, they are visible only inside the body, and they never hold writable storage of their own.
In a fn or op head, each parameter can declare an explicit : type to check arguments against, or omit : type and infer its type and numeric range from the argument passed at each call site. Likewise, a fn head can declare : type after the closing ) to check every returned value against, or omit : type to infer the result type from guard fallbacks and the body's final expression. A mut fn may return a value too, or omit a result when it only changes its receiver. A work declaration still requires : type on every parameter and result (parameterNeedsType / resultTypeNeeded). Each parameter in a signature needs a distinct name (duplicateParameter).
Inside the body, the last line is the expression that produces the function's return value. Before that final line, you can write statements to help work out the answer: local constants with const, local variables with var, if and match statements that update those local variables, and bounded for loops, as Statements describes. Because parameters and local const values are read-only inputs for the duration of the call, trying to assign a new value to either one triggers localImmutable—if you want a working value you can step or update inside the function, copy it into a local var first.
fn middle(low: Number<u8>, high: Number<u8>): Number<u8>
const sum_of = low + high
sum_of / 2
end
fn add_up(values: [4 of Number<u8>]): Number<u16>
var t: Number<u16> = 0
for v in values
t = t + v
end
t
end
mid <- middle(3, 9)
all_of <- add_up([1, 2, 3, 4])
System.screen.border <- Color(mid % 16)
System.screen.background <- Color(all_of % 16)Keep the shape of a function body in mind:
- Every line before the last line must be a statement that does work (like declaring or updating a local variable). Leaving a bare expression on an earlier line where its result is thrown away triggers
resultUnused. - The last line must be an expression that produces the return value; ending a function with a statement triggers
valueBlockEmpty. - When the last line of the body is an
ifor amatch, each branch or arm follows the same pattern: any lines before the branch's final line run as statements first, and the final line of each branch supplies the return value!
enum Size
case little, medium, large
end
fn bonus_for(size: Size): Number<u8>
var points: Number<u8> = 0
match size
little -> points = 1
medium -> points = 3
large -> points = 6
end
if size == .large then points = points + 2 end
match size
little -> points
medium ->
points = points + 1
points
large -> points
end
end
var size: Size = .large
System.screen.border <- Color(bonus_for(size))When directly calling the declaration, you can pass arguments in parameter order (apart(ball, bat)) or attach a parameter's name as an optional label (apart(ball, b: bat)). Supplying an unknown label, repeating a parameter, or passing too many arguments raises badArgument, and leaving out a required parameter raises missingArgument. An argument whose constant value or range cannot fit the parameter's declared type is caught at compile time with literalDoesNotFit; otherwise, Adder checks changing arguments (and the function's return value) at runtime whenever the compiler cannot prove they already fit.
Leave a Calculation Early
Write guard condition else value in a value fn or op to return a fallback when a prerequisite fails:
fn visible(n: Number<u8>): Number<u8>?
guard n > 0 else nil
guard n < 100 else nil
n
endA true test continues with the next line and skips the fallback. A false test evaluates the fallback once and returns from this calculation, including from a function's nested branch or bounded loop. Earlier changes through mut arguments remain; later statements do not run. Every fallback must fit the result type. An omitted result annotation joins the fallbacks with the final expression, so a nil fallback makes the result optional. Keep the final expression even when you use guards.
Use guard item = maybe else nil to unwrap an optional for the remaining body. You can add and item > 0 to test the payload. The name stays read-only and belongs to the successful path; the fallback cannot read it. A guard uses the existing test and branch without copying the input. An op keeps its own memory, clock and reset rules; temporal sources must still be available on their owning ticks.
Handlers use guard condition without a fallback to end that handler's current run. Actions, resultless functions, binding bodies and work bodies do not accept value guards; a work body may call a guarded synchronous helper.
What a Function May Read
To guarantee that a function always returns the same output for the same inputs, a fn can only read:
- its own parameters and local names,
- top-level constants,
- other functions, and
- (when written inside a
structblock) the fields of its own struct.
This rule applies across all functions: free fn declarations as well as a struct's fn, mut fn, and maker functions. A named function cannot reach out to read a top-level var, a binding, or a hardware device directly; trying to do so triggers operationScope.
If a function needs a changing value from outside, such as a sprite's coordinate or a joystick direction, add a parameter and pass the value at the call site. That small habit makes your functions much more flexible too. Consider a Ship struct with a mut fn steer:
struct Ship(x: Number<0...39>)
mut fn steer(dx: Number<-1...1>)
x = x +| dx
end
end
var ship = Ship(20)
when System.screen.frame
ship.steer(System.joystick[2].dx)
endIf steer were wired directly to System.joystick[2].dx inside the struct, every Ship in your game would be stuck on port 2. By taking dx as a parameter, player one's ship can steer with port 2 while player two's ship steers with port 1—or even with an AI routine!
Along the same lines, a function cannot modify a top-level variable (functionSets), roll a random number (randomImpure), use .previous() or any other frame-memory operation (memoryOutsideBinding), pause with wait (waitOutsideHandler), or call itself (recursion).
You can call a function from any binding, handler, op, or later function declared below it.
Member Functions
When you write a function's name as Type.name, it becomes a member function of Type. Its first parameter receives the value written before the dot when you call value.name(...):
struct Position(x: Number<u8>, y: Number<u8>)
fn Position.is_left(value: Position): bool
value.x < 20
end
var position: Position = (x: 10, y: 12)
left <- position.is_left()
System.screen.border <- if left then .white else .black endYou can attach member functions to any type you declare (struct, enum, or type alias), as well as to Number, bool, Event, or even a generic type parameter like T. The first parameter's type must match the type before the dot in the function's name (wrongType), and every field, function, and op on a given type must have a distinct name (memberOverlap).
For structs, you can also write member functions directly inside the struct ... end block, as Struct Blocks shows.
Type Parameters
Want to write a helper function that works on a list of any element type or any length? Use a type parameter or a length parameter right in the function's signature:
- A single capital letter, like
T, stands for any type supplied by the call. - A single small letter inside a list type's length slot, like
nin[n of T], stands for the length of the list passed at the call site—and inside the function body, you can readnas a number!
If the same letter appears more than once in one signature (like fn keep(values: [n of T]): [n of T]), every occurrence stands for the exact same type or length.
fn keep(values: [n of T]): [n of T]
values
end
fn length_of(values: [n of T]): Number<u16>
n
end
const numbers = keep([1, 2, 3])
const flags = keep([true, false])
size <- length_of(numbers)
System.screen.border <- Color(size)A list that grows takes a length parameter the same way, naming its capacity: [up to n of T] accepts a list that grows of any capacity, and the helpers and their callbacks work inside the function.
var crew: [up to 8 of String<16>] = ["Okafor", "Wu", "Brandt"]
var spare: [up to 3 of String<16>] = ["Li"]
fn long_names(names: [up to n of String<16>]): Number<0...255>
count(filter(names, fn(name) -> name.length > 3))
end
total <- long_names(crew) + long_names(spare)
System.screen.content <- Text(total.digits(2)).at(row: 0, col: 0)If a call passes two arguments that disagree on what T or n should be, the compiler catches the mismatch with parameterAgreement.
You can also combine type parameters with function signatures, optionals and events: T? matches an optional of any type, and Event of T matches a value-carrying event of any payload type. Because single capital letters are reserved for type parameters, any type you declare yourself (type, enum, or struct) must have a name at least two letters long (parameterTypeName).
Functions as Values
Read a named free value function without parentheses to use it as a callback. A parameter of type fn(Digit): Digit can apply that callback with positional calls:
type Digit = Number<0...9>
fn twice(transform: fn(Digit): Digit, value: Digit): Digit
transform(transform(value))
end
fn flip(value: Digit): Digit
9 - value
end
const transform: fn(Digit): Digit = flip
named <- twice(transform, 3)
inline <- twice(fn(value: Digit): Digit -> 9 - value, 3)
System.screen.border <- Color(named)
System.screen.background <- Color(inline)Both results are three: flip is applied twice. A function expression uses the same pure-body restrictions as a declaration. Ops, work, mut fn, functions with mut parameters, action-only functions, bare member references and bare built-in references do not supply pure callable values. Wrap a pure member call explicitly when needed, with its receiver passed as an argument or copied as an admitted local snapshot.
Each stored callback has one concrete signature. An inferred helper such as fn identity(value) can fill a typed fn(Digit): Digit slot; taking identity without enough type context asks for an annotation. A declared parameter or result type remains authoritative, so context cannot narrow an explicit broad result. A top-level type alias must be concrete; aliases do not declare generic callbacks.
A generic helper can repeat the same type inside and outside a callback:
type Digit = Number<0...9>
fn twice(transform: fn(T): T, value: T): T
transform(transform(value))
end
fn flip(value: Digit): Digit
9 - value
end
fn identity(value)
value
end
const keep_digit: fn(Digit): Digit = identity
const digit: Digit = 3
flipped <- twice(flip, 3)
unchanged <- twice(keep_digit, digit)
System.screen.border <- Color(flipped)
System.screen.background <- Color(unchanged)A typed ordinary argument fixes T first; otherwise a concrete callback's matching inputs and result can fix it, followed by remaining literals. Concrete evidence must agree: a callback from a byte to Digit and an untyped literal do not choose between those two types. Give the value or callback a concrete annotation in that case. The compiler uses one T throughout each call, with the safe callback compatibility rule; it does not store a universally generic callback.
Passing a Choice to a Helper
A callback is useful when the caller chooses a calculation and a helper applies it. This complete program displays 1368; hold space to display 8631.
type Digit = Number<0...9>
fn keep(value: Digit): Digit
value
end
fn flip(value: Digit): Digit
9 - value
end
fn adjust(values: [4 of Digit], transform: fn(Digit): Digit): [4 of Digit]
map(values, transform)
end
const readings: [4 of Digit] = [1, 3, 6, 8]
selected: fn(Digit): Digit <- if System.keyboard.space then flip else keep end
adjusted <- adjust(readings, selected)
System.screen.text[10][18..<22] <- adjusted |> map(fn(value) -> value.digits(1)[0])adjust accepts the transformation as data and passes it to map. Its signature keeps every input and result within Digit's range, zero to nine. The keyboard chooses between two capture-free functions outside the pure helper. The final pure function expression turns each digit into its printed character.
Use a callback when passing or reusing a calculation makes the program clearer. For a one-off list projection, an explicit fn(value) -> expression is often enough. The map/filter rules explain callback traversal and purity. Payload events keep their separate local-arrow form. Consult the cost report when changing forms: accepting the same input and result types does not promise identical generated code.
Returning Capture-Free Callbacks
A function may select or forward a capture-free callback, and that result can be stored and called normally. Only the chosen if or match arm is evaluated. An unannotated choice needs identical callback signatures; an explicit result signature checks every arm against that contract.
type Digit = Number<0...9>
fn flip(value: Digit): Digit
9 - value
end
fn keep(value: Digit): Digit
value
end
fn choose(reverse: bool): fn(Digit): Digit
if reverse then flip else keep end
end
var reversed: bool = false
selected: fn(Digit): Digit <- choose(reversed)
answer <- selected(3)
System.screen.border <- Color(answer)
when System.keyboard.space.pressed
reversed = not reversed
endDirect and indirect recursive calls remain refused by the current compiler, including cycles through callbacks. This is a current compiler boundary; it requires no author-written fuel or termination proof, and a pure signature still permits ordinary checked failure.
Synchronous Snapshot Captures
An explicit function expression copies admitted local values when it is created. Parameters, local constants, local variables, loop or payload names, pure receiver values and current ordinary binding values may be copied; complete lists and structs are snapshots too. Bounded collection, stream and other resource handles cannot be captured; pass ordinary values read from them instead. Later changes to a local do not change that callback's copy. A binding is read once when the function expression is created. Its producer keeps its own clock, and a failing read fails there before the callback can run. A direct read of a top-level variable, device, temporal operation or resource remains refused: read a permitted value outside the callback and pass or copy that local sample explicitly.
type Digit = Number<0...9>
fn forward(transform: fn(Digit): Digit): fn(Digit): Digit
transform
end
var seen: Digit = 0
when start
var offset: Digit = 1
const shifted: fn(Digit): Digit = fn(value: Digit): Digit -> (value + offset).wrap(0...9)
offset = 7
const forwarded = forward(shifted)
seen = forwarded(3)
end
System.screen.border <- Color(seen)The border receives four, using the copied offset of one. forward returns the existing callback to its still-running caller; it does not create a longer lifetime. A captured callback may pass through synchronous arguments, immutable local aliases, optionals and fixed local aggregates while every copied environment remains live. Returning a newly created callback that captures the returning function's locals or parameters is refused, even through a list, struct, optional or another callback.
Captured callbacks cannot be stored in any var, maintained binding, event, temporal memory, work/job, queue or other longer-lived destination. Their lifetime ends when the creating call or handler finishes, reaches wait, or its active case ends. Create and consume them before that boundary; a local callback needed after a wait is refused. These limits keep copied environments bounded in this first implementation; they do not claim that longer-lived closures are inherently unsafe.
Actions
An action performs synchronous services and has no result. Its explicit type keeps service work separate from a pure fn calculation.
const log = System.screen.region(row: 0, col: 0, width: 20, height: 2)
action show(value: Number<u8>)
log.home()
log.print("VALUE ")
log.print(value.digits(3))
end
when System.keyboard.space.pressed
Number<u8>(7) |> show
endActions may call pure functions and other actions, declare local snapshots, and use conditions and bounded loops. The currently admitted services are print, println, newline, home, clear and cursor.move on a statically known screen or region, plus publish(value) on a statically known Publication in foreground code. They may capture an immutable local value or a static service receiver while its handler or declaring case remains active. They cannot assign authored state, take mutable parameters, read live machine or mutable state, draw random values, use temporal operations, wait, start background work, or retain borrowed capabilities after the call. Pass a live reading as an argument from the handler to make its snapshot explicit.
An action value has type action(T, ...), with no result clause. An inline action(value: T) -> other_action(value) contains one action call. Local action values and finite choices can be passed synchronously to an action parameter. Their parameter domains must safely accept every value the caller supplies; calling through an action value uses positional arguments. A pure function and an action are different types, even when their parameters match.
Observe a Whole Value With do
do(value, perform) captures the complete input, acquires the action once, performs it once, then returns that original input unchanged. It accepts one action(T) and preserves the input's exact type, including optional values and fixed-list holes. A list is passed as one whole value; do also calls the action once for nil or an all-nil list.
const log = System.screen.region(row: 0, col: 0, width: 20, height: 2)
action show(values: [3 of Number<u8>?])
log.home()
log.print("PRESENT ")
log.print(count(values).digits(1))
end
var readings: [3 of Number<u8>?] = [4, nil, 9]
var total: Number<u16> = 0
when System.keyboard.space.pressed
total = readings |> do(show) |> sum
end
System.screen.border <- Color(total % 16)Use a terminal action pipe such as readings |> show when no value should continue. Use do(show) when later pure stages need the original value. Completed service effects remain completed if the action or a following stage fails; assignment of a new result happens only after successful completion. do belongs in a handler or action, and cannot run inside a pure function or a continuous binding.
Ops
An operation (op) is a reusable calculation that remembers earlier frames. Use it for velocities, smooth filters, edge detectors, timers, and bouncing movement. A fn is a pure calculation with no memory of the past. An op looks a lot like a function and ends with its result expression, but its body is made of <- bindings that can look back at previous frames. Use guard condition else value to return a fallback for the current evaluation. Keep retained calculations before a guard when they must advance on every owning tick; a conditional payload cannot supply a temporal source that needs to be available on every tick.
op speed(x)
x - x.previous()
end
bat: Number<0...296> <- (System.joystick[2].dx * 4).sum(from: 136)
moving <- speed(bat) != 0
System.screen.border <- if moving then .yellow else .black end
System.screen.sprite[0] <- (x: bat, y: 170)Just like a function head, an op head declares its parameters inside parentheses and each call supplies the argument values (optionally labeled with the parameter's name). Those parameters are read-only input names written without var, visible only inside the op body and given their fresh value by each call. Like a fn parameter, an op parameter can leave out its : type annotation and automatically adopt the exact type and range of the argument passed at each call. When an op parameter does include a : type, it checks the argument against that type just like a function parameter. The : type after the closing ) is optional too; when written, it sets the result type of the op.
Notice what happens in op speed(x) above: x is a read-only input parameter, not a variable you assign to, yet x.previous() remembers what x was on the previous frame! Remembering prior samples of an input parameter is part of the op call's own frame-to-frame history—it never turns the parameter into writable storage.
Inside an op, you can read its parameters, top-level constants, functions, and other ops (trying to read a top-level var or binding directly raises operationScope). Every line before the final result expression in an op body must be a <- binding (opHolds).
Because an op carries frame-to-frame memory, you call it inside a binding (<-), never inside a when handler, a plain fn, or the starting value of a var (memoryOutsideBinding). And each written op call site in your program gets its own separate memory across frames: if two bindings both call speed(...), each call tracks its own history independently. Even better, if you pass a list to an op parameter that expects a single item, each slot of the list gets its own separate history too!
Remembering With previous
Inside a binding or an op, x.previous() gives the value x had on the previous frame. On the very first frame—before there is a previous frame—x.previous() simply equals the current value of x. If you want a specific starting value on the first frame instead, write x.previous(from: value).
When a binding inside an op (or at the top level) reads its own previous value—or reads the previous value of a binding written further down in the block—you must include from: so the first frame has a known starting point; leaving from: off raises recurrenceNeedsFrom or forwardNeedsFrom.
All of Adder's other history-keeping helpers—such as .sum(), .count(), .cycle(), and .sampled()—are built on this same foundation, and Events and Handlers introduces each of them.
Destination and start
Sometimes an op wants to adapt to the range of whatever binding is receiving its output—for example, a bounce operation that bounces between 0 and 159 for one sprite and between 24 and 255 for another! Inside an op body, the special type name Destination stands for the declared type of the binding receiving the call's result, and Destination.first and Destination.last give the lower and upper ends of that range. Because Destination comes from the receiving binding's annotation, calling such an op in a binding without a : type annotation triggers operationNeedsRange.
Inside an op, the keyword start is a bool that is true while the op works out its very first value (or when it is reset) and false on subsequent frames.
op bounce(begin, speed: Number<-15...15>)
moved <- pos.previous(from: begin) + dir.previous(from: speed)
dir: Number<-15...15> <- if moved < Destination.first or moved > Destination.last then
-dir.previous(from: speed)
else
dir.previous(from: speed)
end
pos: Destination <- if moved < Destination.first then
Destination.first + (Destination.first - moved)
else
if moved > Destination.last then
Destination.last - (moved - Destination.last)
else
moved
end
end
pos
end
x: Number<0...159> <- bounce(150, 4)
System.screen.sprite[0] <- (x: x, y: 50)on: and reset:
Every op—whether you wrote it yourself or it is built into Adder—automatically accepts two optional event arguments at any call site: on: and reset:.
on:sets the pace at which an unqualifiedopsteps forward. Theopworks out its initial value on the first frame, and after that it updates only in frames where theon:event fires. On frames where theon:event does not fire, theopfreezes its result, its internal bindings, and itsprevioushistory in place. An outer binding execution clock instead determines when that binding first runs.reset:restarts theopfresh in any frame where thereset:event fires, even ifon:would otherwise pause it that frame. Theopand its nested ops recompute their first-frame values from current arguments, andstartbecomestrueagain for that frame. History-keeping members follow their documented initialization rules; a sampler restores its already acquired initial value, ornil, as Sampling a Value explains. If bothreset:andon:fire in the same frame,reset:wins.
op travel(initial)
position: Destination <- if start then initial else position.previous(from: initial) +% 1 end
position
end
moving <- System.screen.frame when System.joystick[2].fire
x: Number<0...159> <- travel(20, on: moving, reset: System.keyboard.space.pressed)
System.screen.sprite[0] <- (x: x, y: 50)Both on: and reset: require an event (onNeedsEvent). Plain fn functions do not keep history across frames, so passing on: or reset: to a fn call is flagged with badArgument.
Work
What if you have a big calculation—like generating a dungeon map, tallying a large table, or scoring a board—that takes too many CPU cycles to finish inside a single television frame without delaying the screen update? Declare it with work name(parameters): Result and call it as name(arguments). Calling a work declaration starts a background job that captures its arguments and chips away at the calculation across frames, using the cycles left over in each frame after your regular handlers and outputs finish.
A work body follows the same rules as a fn body. Parameters need explicit types; a calculation with no inputs can use work name(): Result. A work name shares the namespace of ordinary functions and must be declared before its calls. You do not need to sprinkle manual pause points through your loops: the compiler automatically splits the body across loop iterations! A short loop that fits comfortably inside one frame runs in a single part; a longer loop runs a few iterations per frame across several parts; and a loop-free body runs as one part. If a single turn of a loop has an unbounded cost or is too heavy to fit inside a frame at all, the compiler tells you right away and names the loop.
A named pure function or a concrete pure method can contribute resumable loops when its call supplies a whole local initializer (const part = scan(input) or const part = input.scan()), a simple local assignment, or the final value of work. The helper's fixed-range or fixed-list loops can then span frames before the caller continues. Arguments are captured and checked once, in written order. The helper's inputs, locals and result must be numbers, bools, Chars, sets or flags, or fixed lists, records, enums and optionals made from them.
Several work declarations can call the same helper. Each job keeps its own receiver, inputs, loop position, locals and return destination; copying a paused job copies that complete state. Work that already fits keeps its original form, and every expanded call still has to satisfy all storage, frame and deadline limits.
Calls inside larger expressions, lifted or callback calls, mutable helpers, assembly bodies and live-length loops still run as one uninterrupted call. Give a long helper result a local name before combining it with another value: write const part = scan(input) followed by part + 1, rather than scan(input) + 1. For several items, use an explicit bounded loop in work and name each helper result inside the loop instead of lifting the call or passing it as a callback.
type Samples = [4 of Number<u8>]
work tally(input: Samples): Number<u16>
var amount: Number<u16> = 0
for sample in input
amount = amount + sample
end
amount
end
const samples: Samples = [1, 2, 3, 4]
answer: Number<u16>? <- tally(samples)
System.screen.text[0][0..<5] <- if amount = answer then amount.digits(5) else "wait " endBecause a job may take several frames to finish, binding its result with <- produces an optional type T?: the binding holds nil until the first job finishes, then keeps the last finished value while later runs are working. (Giving the binding a non-optional type T raises wrongType.) When its receiver or arguments change during a run, the job finishes with the inputs it captured. After completion, Adder starts another run with the newest inputs if they differ from the captured ones. Intermediate changes do not queue more runs. Changing an input and changing it back before completion needs no rerun. Even inputs that change every frame can produce finished answers.
A new capture can use more of its starting frame. If a work part does not fit after that capture, a bound job can wait for a later frame, keeping the captured inputs. Adder still proves that each part it starts and the screen updates fit the frame.
Several bound jobs take turns in declaration order, one part at a time. The position stays between frames and moves on when its job receives a part or has no work. If the next part does not fit, that job keeps its turn for the next frame. Later jobs can use the leftover time as extras; those extras do not move the waiting position.
With k pending bound jobs, each gets its turn within k frames that have room for the waiting part after foreground work and any completion handlers already owed. A frame with room only for a smaller extra does not count toward that guarantee. New input captures can leave such a frame. This does not change the deadline checks described below, the order inside a job queue, or jobs you drive in a handler.
Work that belongs to a value can remain a member, declared as work Type.name(value: Type, ...): Result and called as value.name(...). Both forms build the same kind of job. You can build a struct directly as the receiver to pass several changing values together:
struct View(x: Number<0...9>, y: Number<0...9>)
work View.total(view: View): Number<u8>
var sum: Number<u8> = 0
for turn in 0..<4
sum = sum + view.x + view.y
end
sum
end
var a: Number<0...9> = 1
var b: Number<0...9> = 2
when System.screen.frame
a = (a + 1) % 10
b = (b + 2) % 10
end
answer: Number<u8>? <- View(x: a, y: b).total()
System.screen.text[0][0..<3] <- (answer ?? 0).digits(3)Each initial run and rerun evaluates and checks its arguments once in written order. A member call captures its receiver first, including constructor fields once in written order. Named arguments keep the order you wrote, even if the declaration lists their parameters differently. The job starts only after the complete capture succeeds. An input that fails its checks stops later input evaluation; a failed replacement keeps the previous completed job and held answer, and earlier completed writes remain in effect. A bound job with no inputs runs once.
answer.running describes the current run, so it can be true while answer still holds an earlier finished value. when answer.changed sees each completed answer once; starting another run keeps that answer and triggers no event. If an optional input becomes nil, captured work still finishes; the binding keeps that answer while it waits for present inputs. Leaving a declaration match case ends this lifetime: reentry starts from nil with current inputs.
A handler triggered only by a finished job result can run in the spare-time service when its complete turn has a proved bound. It does not advance the display-frame clock. An array result bound with <- can use private storage without a large synchronous copy when the compiler proves that storage stays valid for every reader. Jobs stored in variables keep their own complete state and ordinary copies. See the Lava lamp example for a complete image calculation, guarded indexes and a color table built by a compile-time fn.
Draw a large answer directly with pixels(image ?? blank, ...). A constant blank image supplies the picture before the first answer; later runs keep showing the last finished answer. You can also name the selection with shown <- image ?? blank and draw shown:
enum Ink: Color
case mark = .white
end
type Image = [4 of [4 of Ink?]]
work render(): Image
var image: Image = nil
for row in 0..<4
for col in 0..<4
image[row][col] = .mark
end
end
image
end
image: Image? <- render()
const blank: Image = nil
const canvas = System.screen.canvas(multicolor: true)
canvas.background <- .black
canvas.drawings <- [pixels(image ?? blank, x: 0, y: 0, size: 4)]Want a compile-time guarantee that your background job always finishes within a set number of frames? Tack .within(frames: n) onto the call in a binding! The compiler proves from the complete frame cycle budget that each captured run, including a rerun, finishes in n frames or fewer—flagging jobDeadline if it cannot prove the deadline—and the check adds zero runtime cost. A changed input can first wait for the unfinished run, then take up to n more frames in the next run. When a bound job can rerun while another job uses the time left in each frame, Adder refuses a deadline: it cannot prove how long either job waits. A single bound job can prove a deadline for every captured run; several fixed-input jobs retain their finite-work proof.
For several fixed-input jobs, the proof includes the cost of taking turns after each part. Sharing can therefore require a larger frame count than running a job alone.
To drive a job yourself, write var job: Job of T = name(arguments), and in a handler call job.resume() to run one part and get back T?, or call job.finish() to finish the remaining work immediately in that handler turn and get back T. A member call works here too. You can even line up multiple jobs in a queue to run one after another, as Events and Handlers explains.
To start a job you drive yourself over with new inputs, assign a new captured job in a handler. A bound job uses .latest() instead:
work search(target: Number<1...9>): Number<u16>
var total: Number<u16> = 0
for turn in 1...200
total = total + target
end
total
end
var target: Number<1...9> = 1
var job = search(target)
var found: Number<u16>? = nil
when target.changed
job = search(target)
end
when System.screen.frame
if done = job.resume() then found = done end
endA job held in a var keeps its captured inputs until you assign another job; changing target alone does not replace it.
Dropping Stale Runs
When an input changes in the middle of a run, a bound job normally finishes that run and then starts again with the newest inputs. Add .latest() to the call to drop the out-of-date run instead:
work route_to(target: Number<u8>): Number<u16>
var steps: Number<u16> = 0
for turn in 0..<200
steps = steps +% Number<u16>(target)
end
steps
end
var target: Number<u8> = 1
when System.screen.frame
target = target +% 1
end
route: Number<u16>? <- route_to(target).latest()The binding always keeps its last finished answer. A .latest() job also keeps a budget, a number of frames, and counts how many frames it has been waiting for its next answer:
- An input changes during a run. The job sees the change on that frame. If it has waited fewer frames than its budget, it drops the run and starts a new one with the newest inputs on that same frame. Dropping a run does not reset the wait.
- The wait reaches the budget. The job stops dropping. The run in progress finishes with the inputs it captured, even if they keep changing.
- A run finishes. The binding takes the answer, and the wait goes back to zero. The run's length in frames becomes the new budget. If the inputs changed while that run was finishing, the next run starts at once and also finishes. Once a run finishes with no change during it, the job drops stale runs again.
The budget starts as one run's length in frames. If you add .within(frames: n), it starts at n. Otherwise the compiler works it out from the parts it splits a run into: one frame for each part of every bound job's run, since bound jobs share the time left in each frame, plus one. For a single job that runs one part each frame, that is its run's length. The cost report shows each .latest() job's starting budget.
For a run that takes 60 frames, with a budget of 60:
- An input that changes at frame 20 drops the run, and a new run starts at frame 20, so the new answer arrives at about frame 80.
- Changes at frames 30, 34 and 38 each start the run again. The last run starts at frame 38, so the answer arrives at about frame 98, and no out-of-date answer is shown.
- An input that changes every frame drops runs until the job has waited 60 frames. The run that started then finishes at about frame 120, and after that an answer arrives every 60 frames.
| Inputs | Plain <- | With .latest() |
|---|---|---|
| Change once, at frame 20 | Old answer at 60, new answer at 120 | New answer at about 80 |
| Change at frames 30, 34 and 38 | Out-of-date answer at 60, right one at 120 | Right answer at about 98 |
| Change every frame | An answer every 60 frames | First answer at about 120, then every 60 |
A when route.changed handler runs once for each finished answer, and never for a dropped run. route.running stays true while any run is in progress, including across drops. route.progress belongs to the current run, so it is nil from the frame a run is dropped until the new run offers its first progress value. An input that changes and changes back during a run still drops it once; the new run captures the same value.
You can write .latest().within(frames: n) or .within(frames: n).latest(). The compiler proves that each run the job lets finish takes at most n frames, and the budget starts at n, so an answer arrives within 2n frames of the start of the oldest run still waiting for one. As with any bound job, Adder refuses the deadline when the job can rerun while another job shares the time left in each frame, because it cannot prove how long either job waits.
Because .latest() reads the job's inputs again on every frame of a run, it is refused when an input can fail, changes state or keeps history, and when none of the inputs can change. It belongs on a bound job; a job you keep in a var changes only when you assign a new one. Each frame of a .latest() run must also have room to start the run fresh, so a long job made of a single part that fits as a plain binding can be refused with .latest(). The message names the .latest() line. A job with one small input adds a few bytes of storage and a few dozen cycles to the frame bound; the cost report shows the figures.
Work Progress
Write publish value inside a work body to offer an intermediate value of the same type as its final result. Publication keeps the job running; the final expression still supplies the finished answer.
type Samples = [200 of Number<u8>]
work tally(input: Samples): Number<u16>
var amount: Number<u16> = 0
for sample in input
amount = amount + sample
publish amount
end
amount
end
const samples: Samples = 1
answer: Number<u16>? <- tally(samples)
System.screen.text[0][0..<5] <- (answer.progress ?? 0).digits(5)
System.screen.border <- if answer.running then .blue else .green endanswer.progress is T?: nil before the first publication, then the latest complete value sampled at the beginning of a display frame. Every reader in that frame sees that same value, including handlers, reactive bindings and progress.changed. Several publications between frames coalesce to the last one. Input checks between display frames and a handler's resume() or finish() leave the snapshot held until the next display frame. A short job can finish before any frame displays its intermediate steps. In a declaration match case, both captured jobs and scheduled results start with nil progress whenever their case starts, stop running when it ends and restart the next time it matches.
Reading .progress from work that contains no publish is refused (workProgressMissing). Updating a local or returning a value from a helper does not offer progress; put publish value in the work body. A publication in a conditional branch is enough to allow the read, even before that branch runs. Captured job variables that can receive work with publish keep their progress member, including while they hold a job with no publish. An unrelated calculation's publications do not count.
Use a record to offer related fields together, as the nav computer example (examples/nav-computer.adder) does for its checked-through number and prime tally. Ordinary fixed numbers, booleans, characters, bounded strings, named sets, records, lists, optional fields and payload enums can be progress. A String<N> offered with publish, or a record containing one, retains its live length and characters after the work edits its local source. Resources such as Shape and Font, events, streams, job handles and mutable collection containers cannot (workPublication). A value must fit the work's return type under the usual checked boundary rules.
A captured var job = samples.tally() exposes the same read-only job.progress, alongside job.running. Running means its captured work is active and unfinished; a scheduled binding waiting for present inputs is not running. If an input becomes nil during a run, that captured run still finishes. The final optional result and progress are independent: finishing retains the last publication, even when the final answer differs. Recapturing work clears its pending progress, visible as nil at the next frame opening; copies keep independent pending values and continuations.
Work that offers progress stores one optional progress value. Each observed job instance also keeps a frame snapshot, with storage and copies included in the cost report. Programs with native interrupt bodies keep two optional snapshots per observed job and one shared byte to show a complete frame at once. Raster and timer readers see complete values from one frame. Work without publication pays no progress overhead. Publication does not mask interrupts or add a queue.
Type Declarations
Adder gives you three ways to introduce your own types: type aliases, enum declarations, and struct declarations. Just like other declarations, a type must be declared above any line that names it (unknownType). Every type name starts with a capital letter and is at least two letters long; starting a type name with a small letter triggers aliasName, enumName, or structName.
Type Aliases, Enums, and Structs describe the values these types create. While an enum block contains only case lines, a struct can open a block to hold both its fields and its member functions!
Struct Blocks
A struct block lists its fields and functions one per line between struct Name and end. You can either list all the fields on lines inside the block, or put the plain fields in parentheses on the struct Name(...) header line and use the block body for var fields and member functions.
There are two kinds of fields in a struct block:
- Plain fields (
step: Number<u8>) are supplied when you construct the struct, such asScore(step: 10). - Variable fields (
var points: Number<0...999> = 0) start at the initial value written in the declaration. Because they already have their starting value, the struct's maker does not take an argument for them (passing one raisesbadArgument).
Putting any line other than a field or a fn inside a struct block raises structBody.
struct Score
step: Number<u8>
var points: Number<0...999> = 0
mut fn award()
points = points +| step
end
fn text(): [3 of Char]
points.digits(3)
end
fn Score.started(step_size: Number<u8>): Score
Score(step: step_size)
end
end
var score = Score.started(10)
when System.keyboard.space.pressed
score.award()
end
System.screen.text[0][0..<3] <- score.text()Functions inside a struct block come in three flavors:
- Read-only member functions (
fn name(...)): Written without a type prefix before the name. You do not write a parameter for the struct itself—all of the struct's fields and other member functions are automatically in scope by name! A plainfnpromises not to change any of the struct's fields (even indirectly through another call); trying to modify a field inside a plainfnraisesstructMutationUndeclared. - Mutating member functions (
mut fn name(...)): Marked withmutso they can update the struct's fields. Amut fndoes not have to return a value (so its: typeis optional), and handlers can call it on avarstruct, a field of avar, or an element of avarlist. Because it modifies the struct in place, calling amut fninside a binding or on a constant struct is caught withstructChangingPlace. (mut fnis only for struct blocks; writingmut fnat the top level triggersstructMutationMethodOnly.) - Maker functions (
fn StructName.name(...)): Written with the struct's own type name before the dot, likefn Score.started(...). A maker belongs to the type as a whole rather than to an existing instance, so the struct's fields are not in scope inside it, and you call it on the type name (Score.started(10)). Prefixing a function inside a struct block with some other type's name triggersstructMakerOwner.
A mut fn member can use a single assembly body to read and write its own fields by name. Assembly functions can also write explicit mut parameters. The call uses the same place and overlap checks as an ordinary mutating function.
Protocols
A protocol names the fields and member functions a conforming type must supply. Each requirement occupies one line. A function requirement has a signature and no body; the protocol's end closes the declaration.
protocol Located
x: Number
fn distance(target: Number): Number
end
struct Marker: Located
x: Number<0...319>
fn distance(target: Number): Number
target - x
end
end
fn distance(view: Located, target: Number): Number
view.distance(target)
end
const marker = Marker(x: 10)
System.screen.border <- Color(distance(marker, 12))Put one or more protocol names after the type's colon, separated by commas. The compiler names every missing or incompatible requirement, even when the type is unused. A matching shape alone does not declare conformance. An enum can promise ordinary member functions; its payload fields still belong to individual cases.
An enum with associated values puts the value type before its protocols: enum Ink: Color, Scored. Its cases keep their identity and shared color values while its member functions satisfy the protocol.
A field may have a narrower range of the same numeric kind. A member must keep its required argument labels, accept the required inputs and return the required kind of value. A plain fn requirement promises a read-only receiver; mut fn permits receiver changes. Every function requirement states its result type.
A protocol name is a parameter constraint. Each call uses the concrete argument's fields, functions, representation and range checks. Two protocol parameters can receive different conforming types. Protocols do not allocate stored values or introduce runtime lookup. Use a concrete type for a variable, field or result.
The predefined Scrollable protocol requires scroll: (x: Number, y: Number). A named field type such as (x: Number, y: Number) describes a value with those fields in that order. The screen, its regions, canvases and conforming author structs can enter a Scrollable parameter.
The Scrollable world example calls one ahead(view: Scrollable) helper with both an author Camera and its city region. One call tells the camera where to brake; the other names the next stop and its distance in the HUD. The author's y: Number field can stay plain because the region binds the fixed value y: 0.
The formatter keeps requirement signatures, conformance lists and named field types.
Wire Records
A wire describes a message of a fixed number of bytes, such as one a program sends to or receives from another computer. Each field says where it sits: at byte, or for a field that shares a byte, at byte bit b or at byte bits a...b. Numbers wider than a byte are little-endian, low byte first, as the 6510 stores them.
wire Contact(bytes: 4)
x: Number<u8> at 0
y: Number<u8> at 1
active: bool at 3 bit 7
reserved: Number<0...0> at 3 bits 4...6
color: Number<0...15> at 3 bits 0...3
end
wire Stage(bytes: 23)
tag: Number<82...82> at 0
tick: Number<u16> at 1
contacts: [5 of Contact] at 3
end
var received: [23 of Number<u8>] = 0
var tick: Number<u16> = 0
when System.screen.frame
if stage = Stage.decode(received) then tick = stage.tick end
endA wire is a struct, so its values are built and read like any other: Contact(x: 20, y: 90, active: true, reserved: 0, color: 7). Stage.decode(bytes) reads a value from a list of exactly the wire's bytes and gives Stage?: nil if any field is out of its range, never a value that is partly read. value.encode() gives the bytes back, with zeros in any byte no field uses. Both compile to the checks and copies you would write by hand, with one loop for each list.
The types do the checking. A range of one value, such as Number<82...82>, is a tag the bytes must hold, and Number<0...0> marks bits that must be zero. A field can be a number, a bool, a Char (its ASCII code, one byte), another wire, or a fixed list of wires or of those values, laid out one after another. A number placed at bits takes exactly the bits its range needs, low bit first in the little-endian word that starts at its byte; a one-value range may take more bits than its value needs. A list takes whole bytes.
Adder's numbers hold up to 16 bits, so a 32-bit value on the wire is two Number<u16> fields, low half first, named name_low and name_high. Rules that span fields, such as "these two halves are not both zero" or "a name holds only capital letters", are ordinary code after decode.
The compiler refuses fields that overlap, fields that reach past the wire's last byte, bit ranges of the wrong width and lists placed at bits.
adder layout program.adder Stage prints the wire's layout as JSON: each field's byte, bits, width and range, nested wires written out, the 32-bit halves it joins and a fingerprint, so a tool on the other computer can generate its side of the message from the same declaration.
Placing a Value in Memory
Sometimes you want a variable, a table, or an output to live at an exact address in the machine's memory—for instance, to share a buffer with an asm block, place a custom screen matrix on a hardware boundary, or peek and poke a cartridge register. Write name: T at address to pin a value to a fixed memory address:
seen: Number<u8> at 0xC000
shade: Number<u8> at 0xC001 <- seen +% 1
System.screen.border <- Color(seen % 16)Every time your program reads seen, it reads straight from that address in memory, so it immediately sees any byte written there by hardware or assembly code. The address after at must be a whole-number literal (addressNeeded) where the type actually fits within the machine's memory (hardwareInvalid). Unlike a var, a placed value takes no starting = expression. When you attach <- expression, the placed value becomes an output that Adder updates at that address every frame; without <-, a single placed value is read-only from Adder handlers (registerAssigned).
You can also place an entire list at a fixed address, and handlers can freely read and write its elements in place:
tiles: [16 of Number<u8>] at 0xC000
when System.screen.frame
tiles[0] = tiles[1] +% 1
end
System.screen.border <- Color(tiles[0] % 16)If you bind a placed list as the whole text screen, it must start on a 1,024-byte boundary where the video chip can reach it (listOffBoundary).
To keep your program from stepping on its own toes, the compiler checks every at address against your memory layout:
- Placing a list over addresses
0and1(the processor's built-in I/O port) is caught withplacedOnPort. - Two placed values that overlap each other's bytes are caught with
placedOverList. - Any placed value that collides with your compiled code, variables, or runtime routines is caught with
placedOverProgram. - Placed lists get three extra safety checks so a table write never clobbers the machine: they cannot overlap the zero page handed out by the compiler, the processor stack, or the runtime's interrupt vectors (
placedOverRuntime); they cannot overlap the active text screen unless the list is that screen (placedOverScreen); and in a bitmap program, they cannot overlap the picture's memory (placedOverPicture). - A single placed number only checks against your compiled program and other placed values, leaving you free to point it at special addresses as long as you keep it clear of the rest.
A value placed over the video chip's sprite and color registers ($D000 to $D010, $D015, $D017, $D01B to $D01D and $D020 to $D02E) in a program that shows a screen of its own changes with the picture, like the sprites and colors your other lines set: a read answers as the chip would for the last value the program put there (the upper four bits of a color register read as ones), and a write reaches the chip at the top of the next frame. Registers the chip changes by itself or that control interrupts ($D012 to $D014, $D019, $D01A, $D01E and $D01F) stay on the chip. A value over a register the screen already sets from its own lines ($D011, $D016 and $D018) is refused with placedVicOwned, and a value over registers of both kinds with placedVicSplit; place the two kinds as separate values.
Assembly maps out how a compiled Adder program arranges memory.
Include and Project Files
As your game grows, you can split your types, art tables, sound helpers, and cases across multiple files and bring them together with include "path":
include "lib/world"
var lane: Number<0...39> = 0
when System.screen.frame
lane = wrap(lane)
endAny folder containing project.json or main.adder acts as a project (resolving the starting file from project.json's "entry" field such as "src/main.adder", then main.adder, then a lone root-level .adder file); a standalone .adder file treats its own folder as its project root. Running adder new my-game scaffolds a project folder with project.json, src/main.adder, and assets/. Every include and asset path is resolved from that project root folder—even when written inside a file in a subfolder like src/main.adder—and you can leave off the .adder extension, so "lib/world" and "lib/world.adder" refer to the exact same file.
If several files include the same helper file (or even include each other in a circle), Adder includes each file just once, at the spot where it is first mentioned. All files in a project share one flat namespace and follow the same top-to-bottom rule as a single file: a declaration from an included file is ready to use on any line after the include statement. The compiler typechecks every declaration in every included file, and then strips away any unused declarations so your final binary only pays for what your program actually uses.
Include paths use forward slashes / between folder and file names made of ASCII letters, digits, -, _, and ., with no name starting with a dot. Absolute paths, backslashes, empty path parts, and . or .. names are not allowed, and referencing a file that does not exist in the project raises includeMissing.
Write your include lines at the top level of a file, never tucked inside a handler or block.
Declarations in a Match
What a case declares exists only while the case matches. Among declarations, a match or an if holds declarations: bindings, variables, naming lines and handlers. Only the chosen case runs; the other cases cost the frame nothing.
enum Scene
case title, game
end
var scene: Scene = .title
var rounds: Number<0...99> = 0
match scene
title ->
System.screen.border <- .blue
System.screen.text[11][15..<25] <- "PRESS FIRE"
when System.joystick[2].fire.pressed
scene = .game
end
game ->
var time_left: Number<0...9> = 9
System.screen.border <- .green
System.screen.text[0][0..<1] <- time_left.digits(1)
when System.screen.frame.every(50)
time_left = time_left -| 1
end
when start
wait(seconds: 10)
rounds = rounds +| 1
scene = .title
end
endThe value after match may be any value a statement match takes: a number, a named set such as Color, an enum, a bool, an optional, a list or a struct. Every possible value needs a case, or an else -> for the rest. Each case's lines begin on the line below its ->.
A number may have whole-number cases such as 0 ->; a named set uses its bare names, such as red ->. An optional needs nil -> for an absent value. A name pattern such as n -> holds the whole value, or an optional's present value, read-only throughout the case. That case starts again when its named value changes; an else -> case keeps its variables while the value still selects it.
var level: Number<0...9> = 1
match level
0 ->
System.screen.text[0][0..<1] <- "-"
n ->
System.screen.text[0][0..<1] <- n.digits(1)
end
when System.keyboard.space.pressed
level = level +% 1
endA pattern for an enum case that carries fields names them, as a statement match does: over(score) -> or over(score: final) ->. The names hold the case's values, have the fields' types, and can be read anywhere in the case: its bindings, handlers, constants and nested match. A pattern written without fields binds none. The compiler refuses a field the case does not have with unknownField, and an assignment to a field's name with notAssignable.
enum Flow
case title
case over(score: Number<0...99>)
end
var flow: Flow = .title
var points: Number<0...99> = 0
match flow
title ->
System.screen.border <- .blue
when System.joystick[2].fire.pressed
points = points +| 7
flow = .over(score: points)
end
over(score) ->
System.screen.border <- .red
System.screen.text[0][0..<2] <- score.digits(2)
when System.joystick[2].fire.pressed
flow = .title
end
endConditions on Cases
A case may add when condition after its pattern. The first pattern and condition that fit choose the case, just as in a statement match. Conditions are read with the value after match each frame; a condition changing can end one case and start another while the value after match stays equal.
enum Mode
case game
end
var mode: Mode = .game
var lives: Number<0...3> = 3
match mode
game when lives == 0 ->
System.screen.border <- .red
game ->
System.screen.border <- .green
end
when System.keyboard.space.pressed when lives > 0
lives = lives - 1
endWithout a value after match, write ordered when condition -> cases and a final else ->. A when line without the case arrow is a handler inside the case. Either case head may begin with fast or small.
held <- System.joystick[2].fire
match
when held ->
System.screen.border <- .green
else ->
System.screen.border <- .blue
endDeclarations in an If
A declaration if follows the same lifetime rule. A boolean head chooses its true or false case; else if checks heads in order, stopping at the first one that succeeds. An absent else declares nothing while the condition is false.
var paused = false
System.screen.text[10][17..<23] <- "GAME "
if paused then
System.screen.text[10][17..<23] <- "PAUSED"
end
when System.keyboard.space.pressed
paused = not paused
endAn optional head such as if held = item and held > 0 then captures the present value once. Its name is read-only throughout the selected case, and changing that named value starts the case again. Later else if heads are not read after an earlier one succeeds. fast or small before if applies to all its cases; an inner mark decides its own code.
A case may put exactly one declaration after -> on the same line. A handler there can hold its own multi-line body, ending at its own end; another declaration below the completed inline case is statementAfterArm. A one-line if keeps its branches and closing end on that line.
When a Case Starts and Stops
When a handler changes the value after match, the new case begins in the next frame. The case that ends stops its handlers, including the ones that are waiting. The case that begins gives its variables their first values, shows what it binds, and starts its handlers from the top; its start happens in its first frame. A case starts again when the value after match moves to another case, or when a field the case names changes. Setting flow = .over(score: 12) while over(score: 5) runs ends the case and starts it again in the next frame, because over(score) names score. A case that names no fields, such as level -> or else ->, keeps running when only the fields change. A case that names some of its case's fields starts again for those and ignores the others. Each case decides from its own line, so a sibling written with fields does not change it. Setting a value equal to the one it has changes nothing. A variable declared above the match keeps its value as cases change, and a handler outside every case keeps running and waiting.
A case may bind a part of the screen, the border or a sprite that the lines outside the match also bind. While the case shows, its line decides that part; when it ends, the outer line decides it again. Two lines at one level cannot both bind the same part, and the compiler refuses the second with overlap.
What a Case Holds
A case holds bindings, var lines, constants, queues, job result bindings, handlers, and nested match or if blocks that hold declarations. A queue starts empty whenever its case starts. A job queue or spare-time result binding stops when its case ends and starts from the top when the case starts again. Declare the work function above the block.
Types, functions, ops, output declarations, places declared with at, and includes belong to the whole program; declaring one inside a case is caseDeclaration. A case may bind an output or a placed destination declared above it. An outer binding takes over again when it ends. An output's lines give their parts back; a place with no outer binding keeps its last written value.
Blocks beside each other choose their cases independently. Their variables and queues have separate lifetimes and storage. Concurrent cases must bind disjoint cells, parts and voices; the normal checks for canvases and text kinds apply across blocks. A conflict names both lines. Enclosing cases may still show instead of an outer binding. When several cases begin together, their complete images appear together after composition, while all their handlers already run.
A case may also bind System.screen.scroll, columns and rows. The deepest active binding supplies the value stored at the frame border; when it ends the outer binding or the machine's default returns. A nested border or background similarly shows instead of outer bands, which return when it ends.
| Refusal | Key |
|---|---|
a match that holds declarations inside the body of an output | outputMatch |
more declarations below a case with a declaration on its -> line | statementAfterArm |
| a case that cannot begin within a frame's time | caseStartLong, caseStartLate |
A case initializes its state in full within its starting frame. Its picture may take several frames to compose while the previous complete image stays visible. Input service and the new case's handlers continue during composition; an intervening change replaces the waiting image. Costs and the Frame describes the limits.
Events and Handlers
Bindings keep your screen and sound wired up from frame to frame, but a game also needs moments when things happen: a player taps the space bar, a fresh frame begins, a score ticks up, or a timer rings. An event happens in some frames and not in others. A when handler listens for an event and runs its statements in each frame where that event fires. Handlers change remembered program state and invoke device actions; wait and forever belong only in handlers.
var hue: Number<0...15> = 0
when System.keyboard.space.pressed
hue = hue +% 1
end
System.screen.border <- Color(hue)Handlers
A handler starts with when and an event, lists the statements to run, and closes with end. It stands at the top of a program or inside a case, never tucked inside another handler or a function. Putting fast before when spends extra bytes of code to save cycles in that handler alone, as Costs and the Frame describes.
The expression after when must be an event—a moment in time, not an ongoing state. A plain yes-or-no value can stay true across many frames, so if you write one after when, the compiler catches it with onNeedsEvent and suggests the event you probably meant. Write when System.joystick[2].fire, for instance, and the message points you to System.joystick[2].fire.pressed for the single frame the button goes down. When you really do want something to run in every frame while the button is held, filter the frame beat with System.screen.frame when System.joystick[2].fire, as Filters describes.
Inside a handler you write statements: assignments, local var lines, if, match, for, and device actions (see Statements), along with guard, wait, and forever from this chapter. Bindings (<-) live outside handlers, where they stay wired up continuously; if you slip a <- inside a handler, the compiler flags it with actionNeeded and reminds you to assign a variable with = instead.
Inside a handler, if chooses statements to run. Among declarations, if chooses declarations that exist only while their case matches; see Declarations in an If.
Handlers in a Frame
Every television frame follows the same tidy three-step rhythm:
- The machine reads its inputs and decides which events happen in this frame.
- The handlers whose events happened run one after another, from top to bottom in the order you wrote them.
- The outputs—such as the screen, the border, and the sprites—show the fresh values that the handlers left behind.
Because handlers run in written order, each handler sees every change that an earlier handler made in the same frame. Reading an unqualified pure <- binding also uses its current dependencies, including those earlier writes. A binding with memory, such as a running sum or a gated op, or an explicit execution clock, keeps its clocked result until its next update; reading it does not advance it. Suppose a key-press handler sets age = 0 and a frame handler below it adds one: age ends that frame at 1. Put them in the opposite order and age ends the frame at 0. Whenever two cases belong to the same decision, folding them into a single handler makes your intent crystal clear:
var age: Number<0...99> = 5
when System.screen.frame
if System.keyboard.space.pressed then
age = 0
else
age = age +| 1
end
end
System.screen.text[0][0..<2] <- age.digits(2)Notice how System.keyboard.space.pressed works right inside if ... then: an event used as a condition is true in the frames where it happens and false in all the others.
All events for a frame are decided in step 1, before any handler runs. That means when a handler changes a variable, that variable's .changed event fires at the start of the next frame, not midway through the current one.
If a handler stops the program—say, when a calculation steps outside its declared range—the variables it already changed keep their new values, and step 3 never updates the outputs.
Events
Every event has the type Event, or Event of T when it carries a value of type T each time it happens, as Types describes. You can give an event a name with a <- binding, so it stays live across frames, whereas storing an event in a constant or a var is caught with eventConstant.
| Event | Happens | Carries |
|---|---|---|
start | in the first frame of the program, and of each case as it begins | nothing |
System.screen.frame | in every frame, the first one included | nothing |
System.screen.frame.every(n) | in every nth frame | nothing |
key.pressed, key.released | in the frame a key or button goes down, or comes back up | nothing |
System.keyboard.stroke | in the frame a keystroke arrives | a Keystroke |
value.changed | in a frame where value differs from the frame before | nothing |
System.clock.interval(...) | again and again, at a fixed period | nothing |
System.clock.timer(...) | once, after a delay | nothing |
value when event | when event happens | value |
Other events belong to individual devices and queues: shown on a screen region or a canvas, System.keyboard.dropped, and a queue's dropped and completed. The System Device Tree describes each device's events in full.
Start
start fires once, in the very first frame of the program. Inside a case, start fires in the first frame of that case each time the case begins. A when start handler is the natural home for a scripted sequence of steps paced with wait:
var ready: bool = false
when start
wait(seconds: 2)
ready = true
end
System.screen.border <- if ready then Color.green else Color.black endUsed inside an expression, start is true during the first frame of the program (or of its enclosing case) and false thereafter. Inside an op, start is also true in a frame where a reset: event starts the op over from the beginning, as Declarations describes.
Frame Events
System.screen.frame is the steady heartbeat of the machine: it happens in every single frame, including the first. System.screen.frame.every(n) ticks on every nth frame after the first—so every(3) happens in the fourth frame, the seventh, the tenth, and so on.
var x: Number<0...296> = 136
when System.screen.frame
x = x +| System.joystick[2].dx
end
System.screen.sprite[0] <- (x: x, y: 170)Completing Before a Picture Row
Use .deadline(line: N) on a direct frame trigger when its handler must finish before a picture row. The trigger supplies the clock; the deadline asks the compiler to prove when the work finishes. Here the frame handler prepares a color that a later raster interrupt reads:
var next_color: Color = .black
when System.screen.frame.deadline(line: -1)
next_color = .blue
end
when System.screen.interrupt(line: 24)
System.screen.border = next_color
endFrame work opens at picture row 205, in the lower border. The beam then wraps to picture row -51 before reaching the row -1 deadline and the row 24 interrupt. The deadline includes all earlier foreground work of the frame through the marked handler.
The same requirement can protect display-memory preparation. Here a prepared expansion image supplies one row of tile codes and ink bytes:
tiles: [40 of Number<u8>] at 0xE078
inks: [40 of Number<u8>] at 0xD878
when System.screen.frame.deadline(line: -1)
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut tiles, bank: 0, offset: 0)
reu.fetch(into: mut inks, bank: 0, offset: 40)
end
end
endThe compiler proves that the complete frame prefix through this handler finishes before the beginning of picture row -1 after the frame's row-205 opening. It includes earlier handlers, case initialization, the latest allowed start, transfer setup, DMA, sprites and native interrupts on PAL, NTSC and early NTSC. The first frame of a program with a deadline also waits for that border opening. N is a fixed whole picture row from -51 through 204. Cost notes show the complete prefix bound.
A top-level when start is start-up work, not part of that prefix, wherever it stands among the handlers. Its first stretch runs ahead of the first frame's deadline handler, and the program then waits for the next row-205 opening before the handlers that follow it. A long when start, such as one that builds an expansion image, can therefore stand before or after a deadline handler, and the start-up row of the cost report shows what it costs. A when start inside a case runs when the case is entered, in that frame, and counts like the case's other initialization. A native interrupt deadline, described below, still counts a top-level when start, because the interrupt runs while it does.
Keep .deadline(line:) last in the trigger, directly on System.screen.frame or System.screen.interrupt(line:) inside a when header. It belongs to that handler; it cannot be stored in a binding, applied to an alias or combined with an event modifier or or. An ordinary frame header may retain its when condition after the deadline.
The requirement does not change statement order or skip a late update. An unproved boundary is a compile error. Completion requirements apply to normal execution: a terminal checked error keeps its ordinary stop behavior and ends event delivery. Keep decisions and validation before the first visible write: a later checked failure, a guard that can stop, or a branch that can abandon the suffix (including a match arm or guard) is refused. The initial transfer path needs destinations whose bytes the compiler can tell apart, disjoint from one another, and a checked capacity large enough for every address; another writer, waiting or cooperative work prevents admission. Foreground assembly and assembly functions can participate when the compiler can check their complete RAM accesses, bounded calls and return paths. See Assembly With a Completion Deadline for a complete accepted example and the numeric-address change that is refused. Unknown assembly effects, hand-written bindings and output implementations remain outside that boundary. Existing clock-qualified binding, native capture, shared storage and hardware checks still apply independently. Native interference must be total and have a proved return path. An authored asm cycles(...) budget cannot make an unknown native loop bounded: completion admission uses the linked native instructions while keeping hardware DMA charges. Native timers and the watchdog keep their normal delivery behavior. Protected DMA must also fit before native raster triggers whose handlers have no completion deadline, and within the native timer period.
A destination is a list, or a window of a list, that the program declares. A constant index (colors[3], screens[0][3], colors[3..<6]) names the bytes of that element or run. An index found while the program runs stands for the whole list it indexes, as does a field of a record, so the compiler still protects every byte that the place could name. A write or a transfer elsewhere in the program is refused only if it can reach those bytes: row 4 of a matrix beside a protected row 3 is fine, row k is not, and a list at other addresses never conflicts. A call that changes one of its arguments is held to the whole list instead, because the compiler does not follow what the call does to it: poke(mut grid[4]) is refused beside a protected grid[3], while the plain write grid[4][3] = 1 is fine. A list the compiler cannot tell apart, such as a parameter or a list declared inside the handler, is refused.
This is a completion bound. It does not freeze Color RAM, require every interrupt to read a new publication, or prove a complete display protocol. A publication read keeps its own old-or-new value contract. Outputs bound outside the handler still update at their ordinary later point.
An interrupt can name its own completion boundary with the same member:
when System.screen.interrupt(line: -11).deadline(line: 0)
System.screen.border = Color.red
endThis requires the complete interrupt to finish its work and return before picture row 0 in the same hardware frame as its row -11 trigger. Its fixed boundary must be later than the trigger and at most picture row 204. The compiler includes DMA that can delay the interrupt, every later foreground handler, VIC contention and the existing clock and watchdog. It also checks that a delayed interrupt can still arm the next raster point. Every native body must be total, so an interrupt that interferes cannot abandon the promised return. Native masking and return paths stay with the compiler. Every earlier interrupt must also return before the next trigger in its chain, including the gap across the end of the screen. A slow earlier interrupt can therefore cause a refusal even when the marked interrupt itself is short. The compiler also refuses an earlier interrupt whose unproved delay could cross the row-205 start of foreground work or the wrap to picture row -51. Completion bounds use the ordinary frame clock. The complete foreground must also finish before the next row-205 start, even with #allow frame_skips. Checked pure pipes and list calculations keep their ordinary checks; a callback that can fail after a visible write is refused. Action calls and do do not yet have a completion proof and are refused in a program using either deadline form. Once the marked ISR has entered, its normal return cannot be abandoned by a checked failure in native interference.
The initial proof conservatively requires the whole foreground frame to fit that boundary, so unrelated heavy work can also cause a refusal. That work includes a top-level when start, because the interrupt runs while it does. Assembly with an unproved path or effect, interrupt-control mappings and resumable display or job producers keep their conservative refusal. This numeric ISR boundary is an authored requirement; it does not infer a pixel deadline or require a new publication generation.
Presses and Releases
pressed fires in the exact frame a key or button goes down, and released fires in the frame it springs back up. Holding the key or button down across later frames does not fire pressed again. Every key on System.keyboard, a key chosen while the program runs with System.keyboard[key], the fire button of each joystick, and the left and right buttons of the mouse all provide both events.
var key: Key = .a
var presses: Number<0...99> = 0
when System.keyboard[key].pressed or System.mouse.left.pressed
presses = presses +| 1
end
when System.joystick[2].fire.released
key = .b
endA value that is not a key or a button—such as a binding or a joystick's dx—has no pressed event; watch it with changed instead.
Changes
value.changed happens in any frame where a named value differs from what it was in the frame before. You can attach .changed to a variable, a binding, a struct field, or a device reading, provided its value contains no function or action callbacks.
var lives: Number<0...3> = 3
var over: bool = false
when System.keyboard.space.pressed
lives = lives -| 1
end
when lives.changed when lives == 0
over = true
end
System.screen.border <- if over then Color.red else Color.black endA device reading changes in the frame the machine reads its new state. A variable that a handler modifies shows its .changed event in the next frame, because the frame's events are all decided before any handler runs. changed itself carries no value; simply read the value by name inside your handler.
Events That Carry a Value
Some events arrive bearing a gift: System.keyboard.stroke carries a Keystroke, and a queue's batch carries a list. Write when name = event to catch the carried value and give it a name inside the handler:
var shown: Char = .space
when s = System.keyboard.stroke
if c = s.character() then
shown = c
end
end
System.screen.text[12][20] <- shownYou can also pack your own value onto any event with value when event, which creates a new event that carries value in each frame where event happens. The right side of when may even be a yes-or-no value, in which case the event happens in every frame where that condition is true.
points <- 2 when System.keyboard.space.pressed
var score: Number<0...99> = 0
when p = points
score = score +| p
end
System.screen.text[0][0..<2] <- score.digits(2)If an event carries no value, there is nothing to catch, so the compiler flags when name = on a valueless event with eventNoValue.
A stored optional (T?) is a value in memory rather than an event, even though it may hold something: writing when h = held triggers onNeedsEvent, and writing held when e triggers whenSubject. To react when an optional changes, watch held.changed, and inside the handler unwrap it with if h = held then.
Filters
Writing event when condition narrows an event so it happens only in the frames where event happens and condition holds true. The condition can be a yes-or-no expression, or another event (which counts as true in the frames where it fires). You filter a when handler the exact same way, by placing a second when after its event:
var shots: Number<0...99> = 0
var lives: Number<0...3> = 3
when System.keyboard.space.pressed when lives > 0
shots = shots +| 1
end
moving <- System.screen.frame when System.joystick[2].fire
when moving
lives = lives -| 1
endWhen a handler names a carried value, its when filter can inspect that name right on the header line:
var plain: Key = .space
when s = System.keyboard.stroke when not s.shift
plain = s.key
endKeep using when to attach a filter to a handler line; if you write and instead, as in when s = System.keyboard.stroke and s.shift, the compiler nudges you with andOnLine.
Joined Events
a or b combines two events into one that happens in every frame where either a or b happens. If both events carry values of the exact same type, the joined event carries that type too, and when both happen in the same frame, the left-hand value wins. If only one carries a value, or their types differ, the joined event carries nothing.
left <- 1 when System.keyboard.a.pressed
right <- 2 when System.keyboard.d.pressed
var moved: Number<0...2> = 0
when step = (left or right)
moved = step
endIn when name = ..., the name captures only the expression after = up to the first or, and, or when. Writing when step = left or right without parentheses would leave step empty whenever right happened alone, so the compiler catches it with orAfterAssignment; wrapping (left or right) in parentheses joins the two value-carrying events first.
Events and Conditions
Events and yes-or-no (bool) values are distinct kinds of things, and the compiler keeps them from getting tangled in and, or, and not:
orjoins either two events or two yes-or-no values; mixing one of each raisesorNeedsEvents.andworks on yes-or-no values, never on events (andEvents); to require two events in the same frame, filter one by the other withwhen.notflips a yes-or-no value and cannot be applied directly to an event (notEvent).
You can always turn an event into a yes-or-no test by comparing it with nil: event == nil is true in frames where the event stays quiet, and event != nil is true in frames where it happens.
Event Members
Event members have built-in memory across frames—counting presses, cycling through colors, or keeping a running tally—so each one lives in a <- binding where it can keep its own state from frame to frame. Most belong to an event, while sum, sampled, and history can also watch a changing value in every frame. If you place one inside a handler, where it would be forgotten at the end of the block, the compiler catches it with memoryOutsideBinding. By contrast, .changed, .pressed, and .released are maintained once by their source, and every reader shares them freely.
| Member | Gives | In the first frame |
|---|---|---|
e.every(n) | an event that happens on every nth occurrence of e | does not happen |
e.after(n) | an event that happens n frames after e | does not happen |
e.hold(n) | a yes-or-no value that stays true for n frames each time e happens | true if e happens |
e.cooldown(n) | an event that passes e through and then ignores it for the next n - 1 frames | happens if e happens |
b.rising | an event that happens when b steps from false to true | does not happen |
b.falling | an event that happens when b steps from true to false | does not happen |
e.cycle() | the next value of the range or enum at each occurrence, wrapping at the end | the first value |
e.count() | how many times e has happened | 0 |
x.sum(from: v) | a running total of x, clamped to the range | v, or 0 without from: |
e.toggle() | a yes-or-no value that flips at each occurrence | false |
e.countdown(from: v) | a count that goes down by one at each occurrence and stops at the bottom of the range | v |
e.latest() | the value that e carried most recently, as an optional | nil |
x.sampled(on: e) | the complete value x had at the latest occurrence of e, as an optional | nil until the first occurrence, including frame zero |
x.sampled(on: e, from: initial) | the same held sample, with the source's ordinary type | the acquired initial, or the source if e occurs immediately |
x.history(n) | a list of the values of x in the last n frames, newest first, each an optional | all nil |
press <- System.joystick[2].fire.pressed
third <- press.every(3)
presses <- press.count(0...255)
shade <- third.cycle(Color)
bat <- (System.joystick[2].dx * 4).sum(from: 136, in: 0...296)
System.screen.border <- shade
System.screen.sprite[0] <- (x: bat, y: 170)Ranges and Periods
cycle, count, countdown, and sum can take their range either from an inline range argument—such as e.cycle(0..<4), e.count(in: 0...99), or x.sum(from: 136, in: 0...296)—or from the type annotation on the binding that holds them. Passing the range inline lets you chain .cycle(0..<4) directly inside a larger expression like palette[System.screen.frame.every(6).cycle(0..<4)]. e.countdown(from: k) defaults its range to 0...K when k has a known non-negative upper bound K, so hit.countdown(from: 6) > 0 needs no extra range annotation. If neither an inline range nor a binding type supplies the bounds, the compiler reminds you with timeNeedsRange.
cycle steps through whole numbers or an enum, so giving it a fractional range raises wrongType. A count of a recurring frame event or beat needs a possible reset. Otherwise Adder refuses it with countWillOverflow, naming how many counted firings would exceed its range. Use .cycle() with a whole-number range to wrap, or .countdown(from:) to count down and stay at the bottom. Counts on input or other events that may end keep their range checks and report the line if they exceed it; sum clamps to the nearer end instead. sum adds numbers in every frame—or adds the numeric values carried by an event in the frames where it happens—and flags non-numeric inputs with sumNeedsNumber. latest remembers the last value an event carried, so calling it on an event that carries nothing raises timePayload.
The period n in every(n) is a whole number from 1 to 65,535 and may vary while the program runs. The frame count n in after(n) (0 to 65,535) and in hold(n) or cooldown(n) (1 to 65,535) is a constant whole number; all four also accept frames:, seconds:, or ms: labels. Any period or delay outside those bounds is caught with timePeriod. If e happens again before e.after(n) has delivered its delayed tick, the new occurrence replaces the waiting one and starts the n-frame countdown fresh. On any yes-or-no expression b, b.rising (or b.rising()) fires in the frames where b becomes true after being false on the prior frame, and b.falling (or b.falling()) fires when b becomes false after being true.
You can also pace sum and history with an event: x.sum(on: e) adds x only in the frames where e happens, and x.history(n, on: e) records a fresh sample only in those frames.
Sprites at a Raster Row
A complete sprite binding can use on System.screen.interrupt(line:). The foreground prepares its complete value, and the raster service shows that prepared value before the sprite's first fetch. All of the picture's sprite rows retain one completed view, shared with the terrain's screen choice and scroll.
System.screen.sprite[0] on System.screen.interrupt(line: -11) <- (x: 120, y: 80, shape: Shape.square, color: .yellow)
System.screen.sprite[0] on System.screen.interrupt(line: 109) <- (x: 180, y: 140, shape: Shape.square, color: .white)The second row reuses slot 0 after its earlier sprite finishes. The compiler charges preparation, publication, interrupts and every sprite fetch on all three video standards. It refuses a late publication, a still-active previous use, or an unproved competing writer. Interrupts and sprite positions use the same picture-row origin, as do color bands. See Sprites at a Raster Row for lists, supported display updates and collision readings.
Sampling a Value
Use sampled(on: clock, from: initial) when a producer should keep running on its own clock but consumers need a held answer. The initializer is acquired and checked once per instance lifetime. With from:, the result has the source's ordinary type, so consumers need no optional fallback. An optional source stays optional: nil can be its actual captured value. Without from:, the sample starts at nil and has an optional result.
var input: Number<0...1> = 1
pulse <- System.screen.frame.every(2)
total: Number<0...255> <- input.sum(from: 0)
sampled_total <- total.sampled(on: pulse, from: 0)
gated_total: Number<0...255> <- input.sum(from: 0, on: pulse)
System.screen.border <- Color(sampled_total % 16)
System.screen.background <- Color(gated_total % 16)On the first three pulses the sampled total is 2, 4, 6, while the gated total is 1, 2, 3: sampling a running total and slowing down that total are different. One named sampler acquires its complete source once per occurrence, shared by all its readers. Two written sampling calls own two instances.
Initialization happens before the first sampling opportunity. That first occurrence counts, including System.screen.frame in frame zero; a sample of System.screen.frames on that event captures zero immediately. Other temporal members keep their existing first-frame rules.
reset: restores the already acquired initializer, or nil without from:. Reset wins over a simultaneous sample: neither the source nor a changing initializer is acquired on that activation. Reset inherited from an enclosing op follows the same rule. A new instance lifetime, including declaration-case reentry, acquires a new initializer. On a quiet sampling clock the source is not acquired either. Resources and values containing callables cannot be retained by a sampler. Crossing to another execution clock also requires an admitted complete-value lifetime; an ordinary result type alone does not prove it.
Resetting a Member
Every stateful event member accepts reset:, an event that snaps the member back to its starting value. When both the reset event and an update happen in the same frame, the reset wins.
step: Number<0...7> <- System.screen.frame.every(4).cycle(reset: System.keyboard.space.pressed)
System.screen.border <- Color(step)Guard
guard condition checks that a requirement holds before letting the handler continue. When the condition is false, the handler stops for this frame: none of the statements below the guard run, any enclosing forever loop stops as well, and the handler simply waits to start from the top on its next event.
guard name = optional unwraps an optional value for the rest of the handler when it is present, or ends the handler on the spot when it is nil. You can chain and right after the unwrap to test a condition that reads the newly named value:
var held: Number<u8>? = nil
var shown: Number<u8> = 0
when System.keyboard.space.pressed
guard h = held and h > 3
shown = h
end
when System.keyboard.h.pressed
held = 7
endA single guard line can name one optional value; adding a second = on the same line is caught with secondAssignment. Value functions and ops use guard condition else value to return a fallback, as Declarations describes. Handler guards keep the form shown here, without else. Binding bodies, actions and work bodies do not accept value guards.
Wait
wait pauses a handler right where it stands. The handler rests for the remainder of the current frame and picks up on a later frame right after the wait, with all of its local variables still holding the values you left in them.
enum Scene
case title, game
end
var scene: Scene = .title
var credit: bool = false
match scene
title ->
System.screen.text[10][17..<22] <- "ADDER"
System.screen.text[12][13..<26] <- ScreenCode(if credit then "A GAME BY YOU" else " " end)
when start
wait(100)
credit = true
wait System.joystick[2].fire.pressed
scene = .game
end
game ->
System.screen.text[11][16..<23] <- "GAME ON"
endWhile a handler is paused at a wait, its own trigger event goes unheard: if a when ...pressed handler is mid-wait when the player presses that button again, the extra press passes by and is not saved up for later. In any single frame, a waiting handler runs only the stretch of statements between one wait and the next; Costs and the Frame explains how the compiler budgets each stretch.
wait belongs strictly inside a handler. Functions, work members, and bindings compute their answers immediately, so placing a wait or forever inside them raises waitOutsideHandler.
Waiting for Frames
wait(n) pauses for n frames, where n is a whole number from 1 to 65,535. The count n can come from a variable or calculation, as long as its type range starts at 1 or higher. Since a wait must always yield for at least one frame, the compiler flags wait(0) with waitNoFrames, a count whose range includes 0 with waitMayNotPause, and anything other than a whole number or event with waitNeedsEventOrFrames.
Because PAL and NTSC machines tick at different frame rates, a raw frame count runs at the machine's native speed: wait(100) lasts 2 seconds on PAL (50 Hz) and about 1.7 seconds on NTSC (60 Hz).
Waiting for a Time
When you want a pause to feel the same on every television standard, write wait(seconds: t) or wait(ms: t). The compiler converts your time into the nearest whole number of frames for each standard—always at least 1 frame—so the pause is accurate to within half a frame everywhere.
| Wait | PAL | NTSC | Early NTSC |
|---|---|---|---|
wait(seconds: 2) | 100 frames | 120 frames | 122 frames |
wait(ms: 500) | 25 frames | 30 frames | 30 frames |
wait(seconds: 0.25) | 13 frames | 15 frames | 15 frames |
The duration t must be a constant greater than zero, written with either seconds: or ms:. The compiler catches a variable or non-positive time with waitTimeAmount, unknown or doubled unit labels with waitTimeUnit, and a duration that exceeds 65,535 frames on any machine with waitTimeLong.
var lit: bool = false
when start
forever
wait(ms: 500)
lit = not lit
end
end
System.screen.border <- if lit then Color.white else Color.black endWaiting for an Event
wait event pauses the handler until event happens in a later frame. You can wait on any event, including one built with when filters or joined with or. Passing a plain yes-or-no value instead of an event raises waitNeedsEventOrFrames.
var go: bool = false
when start
wait System.keyboard.a.pressed or System.joystick[2].fire.pressed
go = true
endRemember that the machine decides all of a frame's events at the very top of the frame, before any handler runs. Because of that, the event in a wait cannot depend on a name created inside the handler—such as a local var, a for loop counter, or a carried event value—and the compiler flags such references with waitEventReadsLocal.
Waiting for a Timer
A System.clock.timer(...) fires once after its countdown from the start of the program or case, and never fires a second time. To make sure your handler is guaranteed to be listening before the timer goes off, the compiler accepts wait timer only inside a when start handler of the same program or case that declared the timer, outside any forever or for loop, and before any open-ended event wait or any timed wait as long as the timer itself:
ready <- System.clock.timer(seconds: 2)
var go: bool = false
when start
wait ready
go = true
end| Wait | Refused with |
|---|---|
inside forever or for | waitOnTimerLoop |
| in a handler on another event | waitOnTimerElsewhere |
| after a wait that can end after the timer fires | waitOnTimerLate |
| a second time in the same handler | waitOnTimerTwice |
Whenever one of those rules triggers, the compiler message suggests a direct timed wait such as wait(seconds: 2). Waiting on timer or another event is allowed anywhere, because the other event can always wake the handler even if the timer has already passed. If you want a recurring beat you can wait on again and again, use System.clock.interval(...) instead.
Forever
forever repeats its body over and over for as long as its handler stays active. Inside a case, it loops until the case ends; at the top of the program, it loops until the program stops.
Because a handler must yield back to the frame after each stretch of work, every trip around a forever loop must hit a wait on every possible path through its branches. If there is any path through the loop that could spin back to the top without waiting, the compiler catches it with foreverNeverWaits and points out the path that stayed awake.
break is for bounded for loops and cannot be used to jump out of a forever (breakInForever). To stop a forever loop, either end the whole handler with guard or switch to another case. A for loop has a fixed number of turns, so it does not require a wait, though you are welcome to put a wait inside one when you want to pace its steps across frames.
Handlers in a Case
A case's handlers start from the top when it starts matching and stop, waiting ones included, when it stops matching. Declarations in a Match describes the rule and its scope.
Publications
Use a Publication when foreground code needs to give related values to a raster or timer interrupt together. Its initial: value determines the type. Choose an initial state your application can already show: for example, keep the playing area hidden while the HUD is ready.
struct DisplayState(world_visible: bool, border: Color)
const displayed = Publication(initial: DisplayState(world_visible: false, border: .black))
when System.keyboard.space.pressed
displayed.publish(DisplayState(world_visible: true, border: .green))
end
when System.screen.interrupt(line: 24)
const shown = displayed.current
System.screen.border = if shown.world_visible then shown.border else .black end
endpublish(value) takes effect where the call is written. It checks the complete replacement, copies it into private storage and then changes which value readers see. An interrupt during that copy sees the complete earlier value or the complete replacement. A failed check leaves the previous publication current; earlier completed effects keep their ordinary behavior.
A named or inline foreground action can share an ordinary value passed by its caller. Sample changing inputs in the handler and pass them into the action, following the ordinary action rules. Pipelines and collection calculations can build a replacement before publish(value) makes it current.
current is an immutable ordinary value. Capture it once when several fields belong together. A saved value stays unchanged after later publications, including after both private slots have been reused. Copy it into a var to edit your own copy, then call publish(value) when it is ready. Separate reads can see separate completed publications.
REU store and verify can read a current byte list. For fetch or swap, copy it into a var first; current values and their windows stay read-only.
The same primitive can give correlated settings to a native timer:
struct DriverSettings(volume: Number<0...15>, border: Color)
const driver = Publication(initial: DriverSettings(volume: 0, border: .black))
when System.keyboard.space.pressed
driver.publish(DriverSettings(volume: 8, border: .red))
end
when System.clock.interrupt(ms: 10)
const settings = driver.current
System.sound[1].volume = settings.volume
System.screen.border = settings.border
endpublish(value) runs in foreground code. Ordinary fixed numbers, booleans, characters, bounded strings, named sets, records, lists, optionals and payload enums can be values; resources, events, job handles, callbacks and mutable collection services cannot. Both stored values, the selector and all capture/read/copy work count toward the usual storage, frame and interrupt limits. An unused pure declaration adds no publication storage or work.
A publication describes application state. It does not prepare display memory, configure hardware, make Color RAM updates atomic, reserve a destination, give every reader one generation for a whole frame or provide a coherent snapshot of a clock changed by an interrupt. The application remains responsible for preparing the payload its descriptor names. Work Progress uses a different timing rule: its value is held at frame opening.
publish After Preparing Bytes
Here a prepared expansion image supplies two rows. Named windows select the destinations; .deadline(line:) checks the whole update. The publication changes the related display settings only after both transfers finish:
struct Shown(loaded: bool, border: Color)
bytes: [80 of Number<u8>] at 0xE078
inks: [80 of Number<u8>] at 0xD878
row <- bytes[0..<40]
row_inks <- inks[0..<40]
const displayed = Publication(initial: Shown(loaded: false, border: .black))
when System.screen.frame.deadline(line: -1)
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut row, bank: 0, offset: 0)
reu.fetch(into: mut row_inks, bank: 0, offset: 40)
displayed.publish(Shown(loaded: true, border: .green))
end
end
end
when System.screen.interrupt(line: 24)
const shown = displayed.current
System.screen.border = if shown.loaded then shown.border else .black end
endUntil a complete update is shared, the border stays black. The marker records prepared bytes; configuring a renderer and choosing when it reads those bytes remain application decisions.
Queues
A queue is a first-in, first-out line of items: handlers drop items in the back, and your program takes them from the front in the order they arrived. Declare one at the top level with Queue(of: T, capacity: n), giving it a constant name, an item type T, and a maximum capacity from 1 to 65,535.
A queue provides four members:
add(item), used as a statement inside a handler, places a new item at the back of the queue;take(on: System.screen.frame, limit: n), used in a single binding, is an event that fires when the queue is non-empty and carries a list ofnoptional items, oldest first, padded withnilin any slots it could not fill;count()gives the number of items currently waiting in line;droppedis an event that happens in the frame after a full queue had to turn away anadd.
const deliveries = Queue(of: Number<u8>, capacity: 4)
var received: Number<0...999> = 0
var full_turns: Number<0...999> = 0
when System.keyboard.space.pressed
deliveries.add(10)
deliveries.add(20)
deliveries.add(30)
end
batch <- deliveries.take(on: System.screen.frame, limit: 1)
when items = batch
if amount = items[0] then
received = received +| amount
end
end
when deliveries.dropped
full_turns = full_turns +| 1
end
System.screen.text[0][0..<3] <- received.digits(3)Items added by a handler become available to take starting in the next frame. When the queue is empty, take stays quiet and its event does not happen. If a handler calls add when the queue is already at capacity, the newest item is turned away and dropped fires once in the following frame, no matter how many extra items were rejected during that frame.
Only one binding may call take on a given queue—any other readers simply read that binding's name, and a second take on the same queue is caught with queueConsumer. The compiler checks the remaining queue rules under queueForm: a queue must be a constant rather than a var, its capacity must stay within 1 to 65,535, take must live in a binding with on: System.screen.frame and limit:, add must be called inside a handler, and the item type T cannot itself be an optional (since take uses nil to mark empty slots in a batch—wrap an optional inside a struct if an item needs a missing-value state).
Queues of Jobs
A job queue, declared as Queue(of: Job of T, capacity: n), runs background work jobs one after another using the cycles left over in each frame after handlers and outputs finish. Call add(job) in a handler to enqueue a job, such as a call to a work member. As each job finishes, the queue's completed event fires (at most once per frame) carrying that job's result of type T, while dropped reports an overflow just like any other queue. Because the machine drains and runs a job queue automatically, you never call take on one (jobForm). Declarations shows how to write work members and jobs.
type Samples = [4 of Number<u8>]
work tally(input: Samples): Number<u16>
var amount: Number<u16> = 0
for sample in input
amount = amount + sample
end
amount
end
const samples: Samples = [1, 2, 3, 4]
const jobs = Queue(of: Job of Number<u16>, capacity: 2)
var last: Number<u16> = 0
when System.keyboard.space.pressed
jobs.add(tally(samples))
end
when result = jobs.completed
last = result
endStatements
Bindings describe how values flow continuously, while statements are the step-by-step instructions that change state or choose what happens next. Statements live inside the bodies of when handlers, inside mut fn member functions, and inside the for loops of ordinary functions. They run in a straight line from top to bottom, and each statement immediately sees the changes made by the statements above it.
A handler body can also use guard, wait, and forever (see Events and Handlers), as well as asm blocks (see Assembly). A work body can use publish expression to offer a complete intermediate result for the next frame; see Work Progress. This statement is refused in handlers and ordinary functions. The top level of a program holds declarations and handlers. An if there holds declarations with case lifetimes; inside a handler it holds statements. A loose for still needs a handler (loopAtTopLevel).
Assignment
An assignment stores a fresh value into a place in memory—whether that place is a whole variable, a single element of a list, a field of a struct, or a multi-element window of a list. Write the destination place on the left of = and the new value on the right.
The machine evaluates the entire right-hand expression first and then stores the result into the place on the left. The new value must match the place's type (wrongType), and a constant literal that falls outside the place's declared range is caught right away with literalDoesNotFit. When the right-hand side is a calculation whose exact range the compiler cannot prove ahead of time, the program checks the number as it stores it. If the value steps out of range at runtime, the program halts and prints the offending line number on screen, as Values Outside a Range describes.
var lives: Number<0...3> = 3
var score: Number<0...999> = 0
when System.keyboard.space.pressed
score = score +| 10
lives = lives -| 1
end
System.screen.text[0][0..<3] <- score.digits(3)Every assignment takes effect the moment it runs. In the handler below, the second line reads the updated value that the first line just stored:
var taps: Number<0...9> = 0
when System.keyboard.space.pressed
taps = taps +% 1
taps = taps +% 1
end
System.screen.text[0][0..<1] <- taps.digits(1)Adder has a single assignment symbol, =, so every change is spelled out explicitly. Shorthand operators like x += 1 are flagged with actionNeeded—write x = x + 1 (or +% / +|) instead. And if you accidentally assign a variable to itself (x = x), the compiler points out the no-op with selfAssignment.
Elements, Fields and Windows
A place on the left of = can drill into a list element with [index], a struct field with .field, or a chain of both in any order. Only that selected part of the variable changes; the rest of the list or struct stays untouched.
struct Spot(x: Number<0...319>, y: Number<0...199>)
var spot: Spot = (x: 0, y: 0)
var spots: [4 of Spot] = Spot(x: 0, y: 0)
var grid: [3 of [4 of Number<u8>]] = 0
when System.keyboard.space.pressed
spot.x = 10
spots[2].y = 5
grid[1][2] = 7
grid[0] = [1, 2, 3, 4]
endIf an index is known at compile time to fall outside the list, the compiler catches it early with indexOutOfBounds. When an index varies at runtime, the program checks it before writing and halts with the line number if it ever steps out of bounds.
You can also index a list with a range to select a contiguous window of elements, or with two ranges to select a 2D rectangle inside a list of rows, just as in Expressions. Assigning to a window replaces all of its elements at once with a list of the exact same length. Because the right-hand side is read in full before any element is written, you can safely shift a slice of a list onto an overlapping window of the very same list:
var row: [8 of Number<u8>] = 0
var grid: [3 of [4 of Number<u8>]] = 0
var left: Number<0...4> = 0
when System.keyboard.space.pressed
row[left..<(left + 4)] = [9, 9, 9, 9]
row[0...3] = row[1...4]
grid[0..<2, 1..<3] = [[1, 2], [3, 4]]
endA pure constant builder can use the same fixed-width windows with a start calculated by its loop. The compiler fills the finished table at compile time, preserving the same read-before-write rule.
If the list on the right does not match the window's size, the compiler catches the mismatch with wrongLength.
Places That Cannot Be Assigned
Only a var variable—or a field, element, or window inside one—can receive a new value with =. Constants and <- bindings are fixed rules rather than storage boxes, so assigning to either is flagged with notAssignable.
In ordinary foreground code, hardware outputs such as System.screen.border take their values from a top-level or case-level <- binding, never from a statement inside a handler. Writing System.screen.border = .red inside a handler raises notAssignable, and writing System.screen.border <- .red inside a handler raises actionNeeded. To change what an output shows when an event happens, have the handler update a var and wire the output's binding to read that variable:
var alarm: bool = false
when System.keyboard.space.pressed
alarm = not alarm
end
System.screen.border <- if alarm then .red else .black endEvery variable must be declared with var before you assign to it. Assigning to an undeclared name raises assignUndeclared, which keeps a typo on the left of = from silently inventing a brand-new variable.
Likewise, a hardware register declared with at is driven by a <- binding rather than assigned in a foreground handler: assigning to one raises registerAssigned (or hardwareBound when it already has a binding). Declarations shows how placed hardware registers work. Native interrupt handlers can instead write admitted scalar chip registers immediately with =, as Interrupt Routines describes.
Local Variables
Inside a handler, function, or loop, you can declare a temporary working variable with var. A local var always starts with an initial value after =, and may optionally include a : Type annotation.
A local variable is visible from the line that declares it down to the end of its enclosing block—whether that block is the whole handler, one branch of an if, one case of a match, or the body of a for loop. Each time that block runs, the local variable starts fresh with its initial value.
var best: Number<0...9> = 0
when System.keyboard.space.pressed
var steps: Number<0...9> = 0
for i in 0..<3
steps = steps +| 4
end
best = steps
end
System.screen.text[0][0..<1] <- best.digits(1)To keep every name unambiguous on the page, a local variable cannot reuse a name that is already in view in an outer scope (shadowing). And once a block closes with end, its local variables go out of view; referring to one after its block ends raises unknownName.
If Statements
An if statement tests one or more conditions in order and runs the first branch whose condition holds true. Each condition is followed by then, and the entire if closes with a single end.
Writing else if on one line continues the same if statement with another test, so a whole ladder of else if branches still needs only one end at the bottom. An else branch at the end catches the case where none of the conditions held true. When you leave else off and no condition is true, the if statement simply does nothing and execution moves on.
var level: Number<0...99> = 0
var shade: Color = .black
when System.keyboard.space.pressed
level = level +% 7
if level > 60 then
shade = .red
else if level > 30 then
shade = .yellow
else
shade = .green
end
end
System.screen.border <- shadeNote that if you put else on its own line and start a new if on the line below it, you have opened a nested if inside the else branch, and each if will want its own end.
Every if condition must evaluate to a bool (or an event, which acts as a bool for the current frame). The compiler catches a numeric condition with conditionNeedsBool, an unwrapped optional without = with bareOptional, and a missing then keyword with ifNeedsThen.
One-Line Form
For short, punchy decisions, you can place a statement right after then on the very same line. In this one-line form, the whole if—including any else if and else branches, each holding a single statement—stays on that one line and finishes with end.
var taps: Number<0...9> = 0
when System.keyboard.space.pressed
if taps == 9 then taps = 0 else taps = taps + 1 end
end
System.screen.text[0][0..<1] <- taps.digits(1)If a one-line if spills across a newline or tries to pack a for loop onto the line, the compiler flags it with inlineIfLine.
Conditional Names
An if condition can check whether an optional holds a value and unwrap it into a fresh name in a single step. Write if name = optional then: the branch runs only when optional is not nil, and inside that branch name holds the unwrapped value with its plain non-optional type.
Right after the unwrap, you can chain and with an extra test that uses the newly bound name. The machine evaluates the and test only when the optional was present, and runs the branch only when both succeed:
var held: Number<u8>? = nil
var shown: Number<u8> = 0
when System.keyboard.space.pressed
held = 7
end
when System.keyboard.return.pressed
if n = held and n > 3 then
shown = n
else
shown = 0
end
end
System.screen.text[0][0..<3] <- shown.digits(3)The unwrapped name lives only inside the branch opened by that then—it is not in scope inside an else branch or after the if ends. (When you want an unwrapped name to stay in scope for the rest of a handler, reach for guard name = optional, as Events and Handlers describes.)
A conditional unwrap binds a single optional name and must stand at the very start of the condition. The compiler catches malformed unwraps with these messages:
| Form | Key |
|---|---|
if n = held or t > 3 then | orAfterAssignment |
if t > 3 and n = held then | secondAssignment |
if n = held = t then | secondAssignment |
if n = held when t > 1 then | whenInCondition |
if n = taps then, where taps is not optional | alwaysSucceeds |
Match Statements
A match statement compares a value against a list of patterns from top to bottom and runs the statements of the first case that fits. Each case writes its pattern, an optional when condition, an arrow ->, and the statements to run.
You can put a single statement on the same line right after ->, or place a whole block of statements on the lines below ->. Leaving a case empty after -> is fine too—it simply does nothing when matched. Mixing both styles on the same case (putting a statement right after -> and more statements on the lines below it) is caught with statementAfterArm.
enum Mode
case title, playing, over
end
var mode: Mode = .title
var lives: Number<0...3> = 3
when System.keyboard.space.pressed
match mode
title -> mode = .playing
playing when lives == 0 -> mode = .over
playing ->
lives = lives - 1
over ->
lives = 3
mode = .title
end
endA match used as an expression to compute a value uses the exact same pattern rules (see Expressions), while a match at the top of a program switches between cases (see Events and Handlers).
Patterns
Each pattern describes which values its case accepts:
- a bare case name from an enum or named set, such as
title, matches that case; - a case name with fields in parentheses, such as
moving(grab, column: chosen), matches that case and unpacks its fields—either under each field's own name or under a local alias after:; - a literal number,
true,false, ornilmatches that exact value; - any other identifier matches every remaining value and gives it a name inside the case body (and when placed after a
nil ->case on an optional, that name holds the unwrapped non-optional value); elsematches every remaining value without naming it.
struct Spot(x: Number<0...319>, y: Number<0...199>)
enum Drag
case still
case moving(grab: Spot, column: Number<0...39>)
end
var drag: Drag = .still
var column: Number<0...39> = 0
var held: Number<u8>? = nil
var last: Number<u8> = 0
when System.screen.frame
match drag
moving(grab, column: chosen) ->
column = chosen
drag = .still
still ->
end
match held
nil -> last = 0
value -> last = value
end
endEvery Value Needs a Case
Every match must account for all possible values of the expression it tests. If any value is left unhandled, the compiler catches it with missingCoverage and lists the missing cases for you.
Because a when guard on a case might turn out to be false at runtime, a guarded case does not count as handling its pattern for all inputs—you still need an unguarded case (or else) below it. Conversely, writing a second unguarded case for a value that an earlier unguarded case already handled creates dead code, which the compiler flags with duplicateArm. And writing a nil case when the value being matched is not an optional raises nilArm.
Conditions on Cases
Adding when condition after a pattern narrows that case so it matches only when the pattern fits and the condition is true. The condition is free to read any names that the pattern unpacked. If the pattern fits but the when condition is false, the machine keeps scanning down to the remaining cases below.
var hits: Number<0...9> = 0
var shade: Color = .black
when System.keyboard.space.pressed
hits = hits +% 1
match hits
0 -> shade = .black
n when n > 5 -> shade = .red
else -> shade = .green
end
end
System.screen.border <- shadeMatch Without a Value
Write match with nothing after it on the header line when you want a clean multi-way table of boolean conditions. Each arm starts with when condition ->, and the final arm is else ->, which runs if none of the conditions above it held true.
var level: Number<0...99> = 0
var shade: Color = .black
when System.keyboard.space.pressed
level = level +% 9
match
when level > 60 -> shade = .red
when level > 30 -> shade = .yellow
else -> shade = .green
end
end
System.screen.border <- shadeA valueless match always requires at least one when case and a closing else case; leaving either out raises conditionalMatch.
For Loops
A for loop steps through each number in a range or each element in a list from start to finish, running its body once per step. The loop variable named after for holds the current item on each turn.
Over a Range
for i in 0..<8 runs eight turns with i counting from 0 through 7, while the inclusive range for i in 1...3 runs three turns with i counting from 1 through 3. Inside the loop body, i has the exact bounded type Number<low...high> of the range, which means you can use i to index into a list of matching size with zero runtime bounds checks. For a fixed range, both ends are whole numbers known at compile time: literals, constants declared above, or parenthesized arithmetic on them, as Range Bounds describes.
const size = 8
var row: [size of Number<u8>] = 0
when System.keyboard.space.pressed
for i in 0..<size
row[i] = row[i] +% i
end
end
System.screen.text[0][0..<3] <- row[7].digits(3)An exclusive range can also use a changing upper bound, such as for i in 0..<count with count: Number<0...8>. The lower bound must stay fixed in 0...255, and the upper value needs an explicit bounded whole-number domain with a maximum no greater than 255. Exact formats such as Number<u8> do not admit this form; use a bounded range annotation. The upper domain must allow at least one turn. The loop's index type and worst-case cost use the largest possible upper value, while an upper value at or below the start skips the body at run time. The length of a String or a list that grows is such an upper value too: for i in 0..<line.length runs once for each live character, as Over a String or a List That Grows describes. The String or list may be named by any chain of names, members and indexes, as in for i in 0..<lines[row].length; the names that choose the line must not change inside the loop for the walk to be the fast one.
var count: Number<0...8> = 0
var visits: Number<0...8> = 0
when System.keyboard.space.pressed
count = count +% 1
end
when System.screen.frame
visits = 0
for i in 0..<count
visits = visits + 1
end
end
System.screen.border <- Color(visits)Other changing bounds, including either end of an inclusive range, are refused with rangeEndNotFixed. A fractional fixed bound is refused with forRangeNeedsWhole, and a statically empty range (such as 5..<5 or 5...3) with rangeEmpty.
Over a List
for x in xs visits each element of the list xs in order from first to last, giving x the element type of the list. You can loop over a list variable, a list constant, a bracketed list literal, or any expression that produces a list.
var scores: [4 of Number<0...99>] = [3, 1, 4, 1]
var tally: Number<0...999> = 0
when System.keyboard.space.pressed
tally = 0
for s in scores
tally = tally + s
end
end
System.screen.text[0][0..<3] <- tally.digits(3)Because for x in xs reads elements directly from xs as it walks through memory, the loop body cannot modify xs while iterating over it (loopListChanged). When you want to update a list's elements in place, loop over its indices instead—for i in 0..<n—and assign to xs[i].
Trying to run a for loop over something that is neither a range nor a list raises forNeedsList.
Over a String or a List That Grows
for c in line visits the live characters of a String in order, giving c the type Char. for item in xs visits the live items of a list that grows in order, giving item the item type. Only the live part is visited: an empty String or list never runs its body, and a full one visits every place.
var line: String<38> = "abba cabbage"
var bees: Number<0...38> = 0
when System.keyboard.space.pressed
bees = 0
for c in line
if c == Char(98) then bees = bees +| 1 end
end
end
System.screen.text[0][0..<2] <- bees.digits(2)The loop reads the String or list where it lies, so the body cannot change it, whether by an assignment, by append, insert, remove, clear or truncate, or by a function that takes it as a mut argument (loopListChanged). To change it as you go, loop over its positions instead: for i in 0..<line.length runs once for each live character, reads the length once when it starts, and gives i as the position. Because a turn of that loop is always below the length it began with, line[i] is live; a body that makes the String shorter stops the program at the first read past the new end, as any read past the live length does.
var line: String<38> = "abba cabbage"
var spaces: Number<0...38> = 0
when System.keyboard.space.pressed
spaces = 0
for i in 0..<line.length
if line[i] == Char.space then spaces = spaces +| 1 end
end
end
System.screen.text[0][0..<2] <- spaces.digits(2)A loop over the live part costs the read of each character, the loop's own step and what the body does: about 17 cycles a character for a body that only compares it, whether it goes by character or by position, because the length is read once and the loop needs no check of its own. A work body cannot loop over the live part of a String or a list that grows; loop over a fixed range and break at the length there.
The Loop's Name
The loop itself advances its counter or element name at the start of every turn, so the body is not allowed to assign a new value to the loop variable (loopVariableSet). Like any other local variable, the loop's name cannot shadow an existing name in scope, and it disappears once the loop reaches end.
Break
break jumps out of the innermost for loop immediately, continuing execution at the first statement after that loop's end. You can place break inside an if or match within the loop body whenever you want to stop searching early.
var xs: [8 of Number<u8>] = [3, 1, 4, 0, 5, 9, 2, 6]
var before: Number<0...8> = 0
when System.keyboard.space.pressed
before = 0
for x in xs
if x == 0 then break end
before = before + 1
end
end
System.screen.text[0][0..<1] <- before.digits(1)Using break outside of any for loop raises breakOutsideLoop, and using break inside a forever loop raises breakInForever (since a forever loop is ended with guard or a case change instead).
Loops and the Frame
Unless a handler's for loop contains a wait, all of its turns run within a single television frame. Under the default strict policy, the compiler adds up the worst-case cycle cost across all turns and flags a loop that could overrun a supported frame budget with loopOverrun. Costs and the Frame explains how the compiler budgets loop cycles and how a work job can spread a heavy calculation across several frames.
An op computes a streaming signal expression every frame and cannot hold a for loop (loopInOp).
Calls and Device Actions
When a call stands on a line of its own as a statement, it performs an action: striking a note on a sound voice, moving a text cursor, adding an item to a list or queue, or running a mut fn method on a struct.
Here are the built-in statement actions and member calls:
| Call | What it does |
|---|---|
voice.play(tone) | strikes a tone on a sound voice |
voice.release() | lets a voice's note fade |
region.print(text), region.println(text) | prints characters at a region's cursor |
region.newline(), region.home(), region.clear() | moves the cursor, or clears the region |
region.cursor.move(row:, col:) | places a region's cursor |
list.add(value), list[i] = nil | fills the first empty place of a list of optionals, or empties place i and leaves the others where they are |
queue.add(value) | adds a value to a queue |
value.name(...) | calls a mut fn member, which may change value |
const voice = System.sound[1].voice[1]
struct Score
var points: Number<0...999> = 0
mut fn award()
points = points +| 10
end
end
var score = Score()
when System.keyboard.space.pressed
score.award()
voice.play(Tone(.c4, decay: .short))
System.screen.home()
System.screen.print(score.points.digits(3))
end
when System.keyboard.space.released
voice.release()
endThe System Device Tree describes each device's actions and arguments in detail. Device actions like striking a sound note run on an effectful handler path, so calling play inside a pure function is caught with playOutsideOn. Named actions admit the text services listed under Actions.
Action Calls and Pipes
A direct action call or terminal action pipe is a statement with no result: value |> show passes value to the first parameter of show. No following pipe stage or value expression can consume that resultless call. To observe a value and continue calculating with it, write value |> do(show) |> next_step. Both forms evaluate the input before acquiring the action or its later written arguments. See Actions for permitted services and snapshot lifetimes.
Statements in Functions
An ordinary value fn computes its result from its parameters and fixed constants. Inside its body you can declare local var variables and step through for loops. Changing caller state requires an explicit mut parameter; reading or assigning a top-level changing variable directly is refused, and device actions remain off-limits. Declarations describes function declarations in full.
The last line of a value function's body supplies its result when execution reaches it. A guard condition else value can return a fallback earlier, including from a branch or bounded loop; see Leave a Calculation Early. Earlier if and match blocks are statements and may update locals; an earlier if needs no else when its false path has nothing to do. An if or match on the last line instead supplies a value from each branch or case, as Expressions describes. Inside a fn body, const name = value introduces a fixed local calculation; its expression is evaluated when that line runs. Writing name = value updates an existing local var. A fixed local calculation cannot be reassigned and does not update automatically when its inputs change. Trying to assign a second time to a local constant is caught with localImmutable.
fn capped(xs: [4 of Number<u8>]): Number<u16>
var kept: Number<u16> = 0
for x in xs
kept = kept + x
end
if kept > 255 then
kept = 255
end
kept
end
result <- capped([1, 2, 200, 4])
System.screen.text[0][0..<3] <- result.digits(3)A mut fn member can update its struct's fields. Without a result annotation its body contains statements only; with : Type, it finishes with a value expression and returns that value.
The System Device Tree
Open the lid of the machine and you meet its working parts: the video chip painting the television screen, the three-voice sound synthesizer, the keyboard matrix, the control ports waiting for joysticks, paddles or a mouse, and the timers ticking away inside the interface chips. In Adder, each part has a path under System. For example, System.screen.border controls the frame around the picture, and System.joystick[2].fire reads the red button on port 2. You write the full System path wherever you touch a part of the hardware (or give it a short nickname with a constant), and no variable you declare can accidentally shadow a device. This chapter tours the whole machine: every device, its members and their types, what happens when you read or bind each one, and what it costs in bytes and cycles when the cost report measures it.
Almost every member you meet on the device tree works in one of four ways:
| Kind | What a program does with it | Examples |
|---|---|---|
| reading | reads a fresh value that the machine samples at the start of each frame | System.joystick[2].dx, System.paddle[1] |
| event | responds with when, or filters and counts it as a stream | System.screen.frame, System.keyboard.stroke |
| output | binds a live value to it with <- | System.screen.border, System.screen.sprite[0] |
| action | calls it as a step inside a handler | voice.play(tone), region.print(text) |
The remaining members are makers: canvas(...) and region(...) carve out a pixel canvas or a text window on the screen, while System.clock.interval(...) and System.clock.timer(...) set up timed clock events. System.screen.interrupt(line:) and System.clock.interrupt(ms:) are events of a special breed: a when handler for either one is a hardware interrupt routine. To keep your logic steady from top to bottom, the program takes all of its hardware readings once at the very start of each frame, before any handler runs. See Outputs for how output bindings work, and Events and Handlers for everything you can do with events.
Paths
Devices With Numbers
Whenever the machine has more than one of the same unit—two joystick ports, two paddles on a plug, three voices on the sound chip—you pick the one you want with its hardware number in brackets, just like indexing a list. The two control ports on the side of the case are numbered 1 and 2, so the joysticks are System.joystick[1] and System.joystick[2]. If you leave the bracketed number off, the compiler reminds you with instanceNeeded; if you ask for a number the machine does not have, it catches that with noInstance and lists the valid numbers right in the message.
| Device | Numbers |
|---|---|
System.joystick[n] | 1 and 2, the control ports |
System.paddle[n] | 1 and 2, the pair of paddles on control port 1 |
System.sound[n] | 1, the sound chip |
System.sound[1].voice[n] | 1, 2 and 3 |
System.drive[n] | 8 through 11, the IEC disk drives |
You do not have to hard-wire the number if you want the player to pick a port or cycle through voices on the fly: any variable whose range matches those exact numbers can sit inside the brackets. When a program picks a joystick through a variable this way, it samples both control ports every frame so either reading is ready on demand.
var port: Number<1...2> = 2
when System.keyboard.one.pressed
port = 1
end
System.screen.border <- if System.joystick[port].fire then .red else .black endNaming a Device
Use a top-level constant to give a device or one of its branches a shorter alias. For example, give System.joystick[2] a constant name. Because a device is a physical place in the machine rather than data you can copy around, the compiler keeps you from storing a device in a variable, binding it as a value, putting it in a list, or passing it as a function argument (deviceNotValue).
const screen = System.screen
const stick = System.joystick[2]
screen.border <- if stick.fire then .red else .black endDevices Not Built Yet
A few paths on the tree reserve spots for expansion hardware that Adder does not drive yet: System.sound[2] for a second SID chip, System.georam for a RAM expansion cartridge, and System.lightpen for a light pen. If you touch one of them today, the compiler lets you know with notBuilt and links no code for it.
The Screen
System.screen is your television display, driven by the VIC-II video chip. Here is everything hanging off System.screen:
| Member | Kind | Type |
|---|---|---|
border | output | Color |
background | output | Color |
extended_background | output | (first: Color, second: Color, third: Color), described under Extended Background Text |
text | output | [25 of [40 of ScreenCode]], the grid of cells |
content | output | a placed Text, or a list of them |
color | output | [25 of [40 of Color]] |
font | output | Font |
scroll | output | (x: Number, y: Number) in whole pixels, described under Scroll and Window |
columns | output | 40 or 38 |
rows | output | 25 or 24 |
sprite | output | [8 of Sprite], described under Sprites |
sprite_multicolor | output | SpriteMulticolor, with first and second as Color |
frame | event | Event |
frames | reading | Number<u16> |
standard | reading | Number<0...2> |
frame_cycles | reading | Number<16768...19656> |
canvas(...) | maker | a canvas, described under Canvases |
region(...) | maker | a region, described under Regions and Printing |
The whole screen also acts as a text region in its own right, so it comes equipped with all the printing tools of a region: print, println, shown, cursor controls, and the rest.
Border and Background
border sets the color of the wide frame around the active picture, and background sets the paper color behind the characters. Without a binding, the machine greets you with its classic Commodore livery: a light blue border around a deep blue background. Want horizontal stripes of color down the screen? Color Bands shows how to tint individual raster ranges of either one.
var hue: Number<0...15> = 0
when System.keyboard.space.pressed
hue = hue +% 1
end
System.screen.border <- Color(hue)
System.screen.background <- .blackIn the cost report for this little program, the live border binding takes 20 bytes and at most 27 cycles per frame. The constant background <- .black line is set once at start-up: it takes 3 bytes of code and costs 0 cycles during the frame loop.
A program that shows a screen of its own changes the border at the top of a frame, while the bottom border of the picture before is still on screen, so that bottom border can show the new color one picture early.
Text and Ink
text is the classic 25-row by 40-column character grid, where each cell holds one screen code. You can bind the whole 25-by-40 grid at once, a single row, a horizontal slice of a row, or a single cell, using the index and range forms from Expressions. Bind a String<n> with capacity at most N or [N of Char] to an N-cell row or slice and the compiler translates ASCII through the active font, filling the remaining cells with spaces. For example, System.screen.text[10] <- "Ready" fills the rest of row 10 with spaces. Literal padding happens during compilation; changing Strings use bounded runtime fill. A single cell accepts a Char or a one-character literal, such as "A"; [N of ScreenCode] buffers retain their raw glyph slots. Both the row index and the starting column of a slice can move while the program runs; only the slice's width has to be fixed so the compiler knows how many cells to write.
var row: Number<0...24> = 12
when System.joystick[2].fire.pressed
row = row +% 1
end
System.screen.text[row][15..<20] <- "ADDER"
System.screen.text[0][0] <- .block
System.screen.color[row] <- .yellowcolor is the matching 25-by-40 grid of foreground colors—one color nibble for each character cell's lit pixels. Because a single value bound to a list fills every slot of that list, color[row] <- .yellow paints an entire row yellow and color <- .yellow paints every character on the screen. If you bind a list of values instead, its length has to match the target slice; if they disagree, the compiler points out the mismatch with wrongLength.
A list of 25 rows of 40 screen codes is a whole screen. When you bind one to text, or one element of a list of them, or an if or match that chooses among them, the video chip shows the chosen screen where it lies in memory. Changing screens then takes a few cycles, not a copy of 1,000 cells, and only the arm the choice takes is evaluated:
type Page = [25 of [40 of ScreenCode]]
const notice: Page = .space
var decks: [3 of Page] = .space
var deck: Number<0...2> = 0
var ready: bool = false
System.screen.text <- if ready then decks[deck] else notice end
when System.joystick[2].fire.pressed
ready = not ready
deck = deck +% 1
endWhole screens of Char are converted to screen codes every time they change. Declare pages you switch between as ScreenCode, converting them once where you write them, for example const page: Page = ScreenCode(letters).
font selects the character set that shapes every cell on the text screen. By default, Adder starts in Font.lowercase, which gives you both lowercase and capital letters; switching to Font.uppercase gives you uppercase letters alongside the full suite of PETSCII box-drawing and card-suit graphics.
System.screen.font <- Font.uppercase
System.screen.text[12][17..<22] <- "HELLO"If you would rather place strings by row and column without counting out slice lengths by hand, see Text Placement.
Scroll and Window
scroll chooses a camera position in whole pixels. (x: 0, y: 0) shows the original view. Increasing x moves through content to the right; increasing y moves down. The content moves left or up. Negative coordinates move in the opposite direction. The screen, text regions and canvases conform to the predefined Scrollable protocol, whose required field is scroll: (x: Number, y: Number).
The compiler splits each coordinate into cell movement and the chip's remaining pixel offset. Text that needs cell movement takes a fixed matrix as its backing content; its width may exceed the view. Missing cells become spaces, with white ink. Nothing wraps automatically. A program can wrap its own camera with ranged arithmetic.
columns and rows control the video chip's framing aperture. Switching to columns <- 38 and rows <- 24 pulls the border inward by a character width on the sides and a character height at the top and bottom (leaving pixels x 7 to 310 and y 4 to 195 visible), which neatly masks the seam where new characters pop in during a scroll. Each aperture setting takes one of its two fixed sizes, written as a constant in your program.
fn tiles(): [25 of [80 of ScreenCode]]
var cells: [25 of [80 of ScreenCode]] = .space
cells[20] = .block
cells
end
const terrain = tiles()
var camera: Number<0...319> = 0
System.screen.text <- terrain
System.screen.columns <- 38
System.screen.scroll <- (x: camera, y: 0)
when System.screen.frame
camera = camera +% 1
endThe runtime shows one completed view at a frame opening: cells, their colors and the matching camera. It prepares a different cell origin in bounded batches while the old view remains visible. Moving a pixel at a time can use the next prepared cell; a jump or reversal may hold the previous view until preparation finishes. Constant cameras cook their cell shifts during compilation and need no preparation each frame. In a program that shows a screen of its own, the sprites and the border, background and sprite colors change at that same moment, so a sprite stays with the background it belongs to; the cost report names the line of another feature of your program when that feature keeps them changing at the end of the frame's work instead. Outside cases, a constant whole-screen camera and window are configured once at startup and cost 0 cycles per frame; a live camera uses the border stores shown in its cost report. A region still needs its row store each frame to restore its neighbor unless its horizontal camera is a constant multiple of eight. Cases may choose their own fine movement and constant aperture sizes. The deepest active case takes precedence, and its window joins its complete image at publication. A shared changing scroll continues while another case composes its image. If you bind a changing scroll while leaving the screen at the full 40 columns or 25 rows, the cost report adds a friendly reminder on that line noting that the character seam will show at the edge and showing the exact columns <- 38 or rows <- 24 line that hides it. Plain border and background bands, declaration cases and changes between ordinary and multicolor text preserve the selected scroll and window. Bands whose interrupt needs picture row 205 or later, authored assembly and custom interrupts retain the windowRaster check. On a canvas, bind picture.scroll before its drawings; it subtracts the pixel camera from placed pictures, fills and pixel rows. Pictures and fills keep their usual clipping and placement checks; pixel rows still require their complete translated rectangle to fit. Paths and circles with a canvas camera currently refuse because their translated placement has no proof. The root text screen's scroll does not move a bitmap.
Scrolling terrain above a fixed HUD
const world = System.screen.region(row: 0, height: 24)
const hud = System.screen.region(row: 24, height: 1)
world.text <- terrain
world.scroll <- (x: camera, y: 0)
hud.text <- "STATUS"The first admitted scrolling text region is a full-width band at the top, above its fixed neighbor, outside declaration cases. Its vertical camera stays zero. One fixed screen font can be a machine font or a custom font. Region-local fonts need a separate proof of the shared character set.
The service fires on the terrain's last pixel line and changes the horizontal offset in the border, after those pixels finish and before the HUD starts fetching. The HUD shows all 40 columns even when System.screen.columns <- 38 hides the terrain's moving edges. The compiler proves both the earliest and latest store, including taken-branch interrupt latency, on PAL, NTSC and early NTSC. It latches CIA 2's NMI at startup so RESTORE cannot delay that store. A sprite's fetches must end before the line preceding the service or begin after the following line; unproved DMA overlap refuses.
Other rectangles, changing fonts, unproved interrupt writers and unproved vertical fetches receive scrollView with the missing condition. Open Scrollable world in the Lab for a monorail ride across a 160-column city in a machine font, with a HUD that names the next stop. Its one ahead helper reads the requested camera position to brake at each stop and world.scroll.x to name the stop on the fixed status row. See Costs and the Frame for the bounds and service cost.
Frames and the Video Standard
System.screen.frame is the heartbeat of an Adder program: it fires once at the beginning of every television frame—50 times a second on a European (PAL) machine and 60 times a second on a North American (NTSC) machine. System.screen.frames is a 16-bit counter that ticks up from 0 on each frame and wraps cleanly from 65,535 back to 0.
When your program boots, it measures the video chip against the timer to see what kind of machine it is running on. standard reports what it found: 0 for PAL, 1 for standard NTSC, and 2 for the early 64-cycle-per-line NTSC video chip found in the earliest silver-label machines. frame_cycles gives you the exact processor cycle budget of one frame on that hardware: 19,656, 17,095, or 16,768. Both values are measured once at start-up and stay constant for the life of the run.
var ticks: Number<0...9> = 0
when System.screen.frame
ticks = ticks +% 1
end
System.screen.border <- if System.screen.standard == 0 then .blue else .red end
System.screen.background <- Color(System.screen.frames % 16)
System.screen.text[0][0..<1] <- ticks.digits(1)Color Bands
Want a sunset sky behind your title screen, a black status bar at the top, or a copper-style striped border? Putting a pixel-row range in brackets after border or background creates a color band that paints just those scanlines. Row 0 is the very first pixel row of the main 200-line picture window, so the picture itself runs from row 0 down to row 199. All screen vertical positions share these picture rows: Sprite.y, color-band edges, interrupt(line:) and deadline(line:). Picture row 0 is hardware raster line 51 on PAL, NTSC and early NTSC; the compiler makes that conversion. Negative rows are above the picture, and rows 200 and above are below it. Raw register operands in asm still use chip values. Because the border extends above and below the main window, a border band can also reach into rows -51 to -1 in the upper border and rows 200 to 210 in the lower border—the visible border rows shared by every PAL and NTSC machine. A background band stays within the main window, rows 0 to 199.
var hue: Number<0...15> = 0
when System.keyboard.space.pressed
hue = hue +% 1
end
System.screen.border <- .blue
System.screen.border[-51..<0] <- .black
System.screen.border[49...98] <- Color(hue)
System.screen.background[96...199] <- .greenYou write the band's vertical span as a single row or a range (a...b or a..<b) with constant endpoints known at compile time. The color expression on the right of <- can be as lively as you like; when it changes, the new color appears on those scanlines starting on the next frame. An unindexed binding on the same output (like System.screen.border <- .blue above) sets the base color for every row not claimed by a band; if you omit the base binding, unclaimed rows keep the machine's default startup color. Two bands on the same output cannot overlap on the same scanline.
To make sure every raster split fires cleanly on every television standard, the compiler checks your band ranges up front:
- if a band endpoint is a changing variable rather than a compile-time constant, it flags
rangeEndNotFixed; - if a row falls outside the valid range (
-51...210forborder,0...199forbackground), it flagsrasterSelection; - if a border band reaches past row
210into scanlines that only PAL televisions have, it flagsrasterLine; - if two bands on the same output share a scanline, it flags
overlap.
Under the hood, each top and bottom edge of a color band is driven by a hardware raster interrupt: the video chip taps the processor on the shoulder at that exact scanline to swap the color register. In a program with a single border band, the cost report charges 67 bytes and 114 cycles per frame for the pair of interrupts. You can freely mix color bands with fixed-line interrupt routines—the compiler weaves them into a single sorted raster chain. However, a self-scheduling interrupt routine that writes its own raster lines needs full control of the raster interrupt vector (rasterOwner), and because bands use the hardware timer setup to stabilize their timing, they cannot share a program with a clock interval or timer (periodicOwnership).
Regions and Printing
A region is a rectangular window on the text screen with its own independent cursor, ink color, wrapping rules, and scrolling. System.screen itself is the root region spanning all 25 rows and 40 columns, and calling parent.region(row:, col:, width:, height:) carves out a sub-window inside any parent region.
All four geometry arguments are compile-time constants measured in character cells from the parent region's top-left corner. If you leave col out, it defaults to 0; if you leave width or height out, the region stretches to the right or bottom edge of its parent. The compiler checks your window layout at build time: if a region sticks out past its parent's edges, you get regionOutside, and if two sibling regions of the same parent claim the same character cell, you get regionOverlap.
const status = System.screen.region(row: 0, height: 1)
const log = System.screen.region(row: 1, height: 3, width: 12)
var entries: Number<0...999> = 0
status.text[0] <- "COUNT:"
when start
log.cursor.color = .light_green
end
when System.screen.frame.every(30)
entries = entries +% 1
log.println(entries.digits(3))
endWhen you declare a region inside a case, it belongs to that case: it starts fresh and blank each time the case begins, and when the case finishes, whatever was on the screen underneath shows through again. See Events and Handlers for how cases work.
Region Members
| Member | Kind | What it does |
|---|---|---|
print(text) | action | prints the characters at the cursor and leaves the cursor right after them |
println(text) | action | prints the characters, then advances the cursor to the start of the next line |
newline() | action | moves the cursor to the start of the next line |
home() | action | moves the cursor back to the region's top-left cell (0, 0) |
clear() | action | fills the region with spaces and moves the cursor home |
wrap | variable | a TextWrap: .character (the starting setting), .word or .hyphenated |
cursor.row, cursor.col | reading | the cell coordinates where the next printed character will land |
cursor.move(row:, col:) | action | teleports the cursor to a specific cell inside the region |
cursor.color | variable | the Color used for characters printed from now on |
cursor.reverse | variable | a bool: whether newly printed characters appear in reverse video |
text | reading / output | the region's grid of cells, with local row and column indices |
color | reading / output | the colors of those cells, with the same local indices |
scroll | reading / output | the current whole-pixel (x:, y:) camera, initially (x: 0, y: 0) |
content | output | takes a placed Text, positioned in the region's own coordinates |
shown | event | fires when everything printed to the region has been copied onto the visible screen |
region(...) | maker | carves out a smaller sub-region inside this one |
Use status.text[0] <- "READY" to fill one local row, or world.color[3] <- .yellow for its local color row. A short literal fills the rest of its row with spaces, just as on System.screen. Index checks use the region's own height and width, so a changing index cannot reach a neighboring region. Read world.scroll.x directly when a calculation needs the current camera.
Inside any when handler, you can update wrap, cursor.color, and cursor.reverse with =, and your settings stay in effect for future prints until you change them again.
Printing
print and println accept any list of Char or ScreenCode values, including string literals. Adder never guesses how many digits or leading spaces you want for a number, so passing a bare number to print is caught with printList—just call .digits(n) on the number to format it into characters first.
diagonal <- ScreenCode(Number.random(77...78))
System.screen.font <- Font.uppercase
when System.screen.frame
System.screen.print([diagonal])
endAs characters stream into a region, a line that reaches the right edge wraps onto the row below. When the cursor is at the bottom row and needs a fresh line, the region scrolls its contents up by one row and blanks the new bottom line. A trailing newline at the bottom of a region delays scrolling until the next character is printed. The last printed line stays visible until more text arrives. In .word wrap mode, words that would cross the right margin hop down to the next row intact, while a single word wider than the entire region splits across rows. Strings hold visible characters rather than hidden control codes: use the explicit newline(), home(), and clear() actions whenever you want to move the cursor or wipe the window.
Every print formats its characters into the region's buffer right inside the handler that called it, during that same frame. The compiler calculates the worst-case cycle cost of the longest string that print can receive—including word wrapping and scrolling—and verifies that the frame budget can hold it, as explained in Costs and the Frame. If a large region takes more than one frame to copy its buffer out to the screen, you can trigger your next batch of output on shown to print as fast as the display can keep up:
when System.screen.shown
System.screen.println("HELLO, WORLD!")
endPartial region updates
partial before a region declaration permits its updates to appear one complete row at a time. Each row shown keeps characters and ink from the same captured state; a later print cannot change a waiting row. Other areas keep their whole-image promise.
partial const log = System.screen.region(row: 12, width: 8, height: 3)
when log.shown
log.println("OK")
endIt combines with one fast or small preference, in either order. Plain printing regions with a fixed font use a private row, prepared in one frame and shown behind the beam in another. Shared colors and unmarked colored neighbors keep their existing updates; cases, overlapping layers and changing fonts retain their whole-image route. The cost report gives a shared showing bound after the final write; continuing writes can replace work. A hires partial canvas declared outside cases can show complete pixel rows and their cell colors while placed pictures change. Its row is captured before the following frame shows it; the report bounds when all its rows settle after the final change. An outline-only hires canvas keeps its ordinary resumable preparation in a private image, then captures the complete rows; its report includes the preparation and row-pass debt. A partial printing region using the default machine font beside a hires canvas with constant color/background and no drawing list also captures its logical characters and inks into a private glyph row, then shows that complete row at the following border. Its cursor, reverse, wrap and entered-line printing retain their ordinary meanings. An unmarked printing region in that fixed backdrop uses a real second bitmap and color matrix, keeps the old complete picture while rows are prepared, then switches the complete image at a border. It is refused with actual storage quantities when that second image cannot fit. Hidden catch-up after a flip does not keep the already complete visible region waiting. An unmarked default-font log can also share a whole hires picture with one root placed-picture engine and fixed color/background: each accepted drawing and captured log image finishes together while newer requests wait for the next picture. Source handlers keep running during hidden catch-up. Mixed picture/outline lists, multicolor canvases, canvases in cases and the remaining bitmap printing combinations still need their joined update paths and remain refused.
Text Placement
While print acts like a teletype cursor, Text(...) is for declarative labels and text boxes: Text(content) holds the characters, and the words after it place and style them. Binding a placed text to System.screen.content (or a region's .content) keeps it live on screen, while System.screen.text stays the grid of cells. You can also bind a list of placed texts at once; if two overlap, a later item in the list paints over an earlier one.
var score: Number<0...999> = 0
when System.keyboard.space.pressed
score = score +| 10
end
System.screen.content <- [
Text("SCORE").at(row: 2, col: 4),
Text(score.digits(3)).at(row: 2, col: 10),
]| Word | Takes | Meaning |
|---|---|---|
Text(content) | text | a string, a list of Char or ScreenCode, or an if/match choosing between them |
.at(row:, col:) | whole numbers | the top-left cell, which may move while the program runs; every placed text has one |
.width(columns) | a positive constant | the column width of a fixed-size view |
.height(rows) | a positive constant | the row height of a view; requires .width |
.wrapped(policy) | TextWrap | .character, .word or .hyphenated; wrapping requires both .width and .height, and a view without .wrapped clips |
.aligned(alignment) | TextAlignment | .leading (the default), .center, .trailing or .justified |
.ink(color) | Color | optional foreground color for the placement's cells |
.cursor(style) | CursorStyle | .steady, .flashing or .hidden, for a fixed screen view of the keyboard line |
Each word applies once to a text, in any order. Just as with print, a bare number is not content—use .digits(n) to turn it into characters first. To place several strings and values side by side on the same row without counting column offsets by hand, join them with ++ and place the whole line. Each part is laid out immediately after the previous one's width, and .ink(color) on a part gives just those cells their own color while the rest use the line's .ink (if any). A joined line takes .at(...) and .ink(...); each part keeps its own width.
var score: Number<0...9999> = 42
System.screen.content <- (Text("SCORE ") ++ Text(score.digits(4)).ink(.yellow)).at(row: 0, col: 2).ink(.light_blue)Text placements and region print/println consume a String's live prefix, including trailing spaces. Captured Text keeps its characters after the source changes; a shorter update restores the old tail. Char controls need an explicit presentation conversion or produce the ordinary glyph diagnostic. A joined Text part advances by its static capacity; use one concatenated String when the next part should immediately follow its live content.
The compiler checks the box geometry up front and flags textLayout if a placement's rectangle would spill off the screen, if you give a .height without a .width, or if you ask for .wrapped without both .width and .height.
A placement without a .width is a label: it is simply as wide as its current content (clipped at the right edge of the screen). If a label's content shrinks—say, when a message changes from a long word to a short one—Adder automatically restores whatever characters lay underneath the vacated cells (or fills them with spaces). A placement with a .width is a view: a rectangular box that holds its size steady as its content changes, padding any unused cells with spaces. By default a view clips at its right edge; with .wrapped(...), long text flows onto the rows below inside the box. .word breaks lines cleanly at spaces between words, and .hyphenated also hyphenates any single word that is wider than the view itself.
When you omit .ink, Text touches only character cells and foreground colors come from your color bindings. If a large multi-row layout takes more than a single frame to typeset and copy to the screen, Adder spreads the redraw across frames automatically, and if the content changes again in the meantime, the newest layout cleanly supersedes any unfinished redraw.
Alignment and Justification
.aligned(a) takes a TextAlignment—.leading, .center, .trailing or .justified—and positions each line within the view's width. .justified spreads extra spaces evenly between words on every wrapped line that continues onto the row below (leaving the final line of a paragraph ragged, just like book typography); it requires .word or .hyphenated wrapping. A text takes one .aligned; a text you keep under a name can be aligned again, and the last alignment wins.
System.screen.content <- [
Text("RADIO").at(row: 0, col: 0).width(16).aligned(.center),
Text("A B C LONGWORD").at(row: 2, col: 0).width(10).height(2).wrapped(.word).aligned(.justified),
]Programs that use Text, TextWrap, TextAlignment, CursorStyle, or region printing automatically link in Adder's text layout engine; programs that don't use them pay zero bytes for it.
Multicolor Text
Bind System.screen.multicolor to choose the two shared colors for the whole text screen. This switches the video chip into multicolor character mode. A cell with ordinary ink still uses hires pixels; .multicolor(color) selects pairs of horizontal pixels for that cell. Both choices take a color from the first eight palette colors (Color.black through Color.yellow), because the cell's color bit also records which choice it uses.
System.screen.multicolor <- (first: .green, second: .brown)
System.screen.text[0][0..<2] <- "AB"
System.screen.color[0][0] <- .yellow
System.screen.color[0][1] <- .multicolor(.yellow)The shared colors may follow changing values and appear together at the frame border. A cell can choose hires or multicolor ink with if or a named binding. The compiler refuses a color outside the first eight for either choice. The whole-screen binding cannot be chosen separately inside a case until its text, ink, colors and mode can change together.
Calling System.screen.region(multicolor: true) also selects multicolor text for a region. Its ink uses the first eight colors; the compiler adds the cell's selection bit. Hires text beside that region keeps to the first eight colors too. A color from Color.orange through Color.light_grey is reported with multicolorInk or multicolorBeside, as appropriate.
const colors = System.screen.region(multicolor: true)
System.screen.text[10][14..<20] <- "COLORS"
System.screen.color[10][14..<20] <- .yellowEach case can display either multicolor text or a bitmap canvas, and a multicolor region declared inside a case applies only while that case is active.
Extended Background Text
Bind System.screen.extended_background to (first: Color, second: Color, third: Color) to switch the video chip into Extended Background Color Mode. Alongside System.screen.background (background 0), each character cell chooses one of four background colors (0...3) in the upper two bits of its ScreenCode while picking from the first 64 glyphs (0...63) of the active font in the lower six bits, packed with ScreenCode(glyph: g, background: bg). Extended background text cannot be combined with a bitmap canvas or multicolor text in the same active scope.
Canvases
When character cells are not enough and you want to plot individual pixels, stamps, outlines, and tiled fills, a canvas switches the video chip into bitmapped graphics mode—320 pixels wide by 200 pixels tall. You declare one with System.screen.canvas(...) and bind its members through the constant name you give it.
| Member | Kind | Type |
|---|---|---|
drawings | output | a list of Drawing? |
color | output | Color, .white by default |
background | output | Color; per-cell in hires, shared in multicolor |
shown | event | Event |
| Argument | Meaning |
|---|---|
multicolor: true | double-wide pixels (160 across by 200 down) with more colors per cell |
row, col | top-left character cell of the canvas (0 when left out) |
width, height | size of the canvas in character cells (fills the rest of the screen when left out) |
const picture = System.screen.canvas()
const badge = Picture(["XXXXXXXX", "X......X", "X......X", "XXXXXXXX"])
x: Number<0...312> <- System.joystick[2].dx.sum(from: 80)
picture.color <- .yellow
picture.background <- .blue
picture.drawings <- [badge.place(x: x, y: 40)]
System.screen.sprite[0] <- (x: 160, y: 130, color: .white)On a standard high-resolution (hires) canvas, each 8-by-8 pixel cell displays two colors: color for lit (1) pixels and background for clear (0) pixels. On a multicolor: true canvas, picture.background sets the shared System.screen.background behind every cell. A full hires canvas uses its per-cell background. Bind canvas.background in either mode. On a hires canvas, use this per-cell output rather than System.screen.background (bitmapBackground).
Because the video chip uses the screen's memory for bitmap pixels, a canvas replaces the character grid where it sits. In a case with a full-screen canvas, touching System.screen.text or System.screen.font is flagged with bitmapText; if the canvas is a smaller window (row:, col:, width:, height:), touching System.screen.text alongside it is flagged with canvasText. A case can hold at most one canvas (canvasMore). A canvas declared at the top level of the program stays on screen for the whole run, while a canvas declared inside a case appears only while that case is active. Hardware sprites float right over a canvas just as they do over text.
const map = System.screen.canvas(row: 2, col: 10, width: 20, height: 12)
map.color <- .green
map.background <- .blackPixel coordinates inside a canvas are always measured from the canvas's own top-left corner (0, 0), so the 20-cell-wide map canvas above is 160 pixels wide (x from 0 to 159). If a canvas's row, col, width, and height would push it past the 25-by-40 screen grid, the compiler catches it with canvasLeaves.
Drawings
drawings takes a list of drawing commands, rendered in list order so later items paint on top of earlier ones. Any slot in the list can evaluate to nil (giving the slot type Drawing?), and whenever a slot turns nil, the canvas cleanly erases that drawing and restores whatever was behind it. Helper functions can build and return drawings, and ++ concatenates lists of drawings together. Helpers can return a single Drawing? as well. map(values, helper) and zip_with(left, right, helper) build drawing lists in one bounded loop; missing inputs skip the helper, and a nil result draws nothing. Each slot retains its own geometry without another copy of the helper's code. Pixel helpers currently need calls written in the drawing list. Use one pixels field for a grid; mapped pixel helpers receive a source diagnostic until their complete capture and drawing path can be proved.
| Drawing | What it draws |
|---|---|
pixels(values, x:, y:, size:) | draws fixed rectangular rows of colors or color names as square pixels |
pixels(values, x:, y:, pixel_width:, pixel_height:) | draws those rows with separate fixed pixel dimensions |
picture.place(x:, y:) | stamps a picture with its top-left corner at pixel (x, y) |
picture.fill(x:, y:, width:, height:) | tiles a picture across a pixel rectangle, cropping the last repeat cleanly |
points.outline() | draws straight lines connecting a list of Point values and closes the polygon back to the first point |
line(from: Point, to: Point) | draws one straight line between its two endpoints |
points.lines() | joins consecutive Points without a closing edge |
circle(x:, y:, radius:) | draws an integer midpoint circle that fits completely inside the canvas |
points.outline().inverted | draws a closed polygon outline that XOR-inverts the pixels underneath it, rendered on top of normal drawings |
Text(content).font(face).place(x:, y:) | stamps a string using 8-by-8 character glyphs from a font at pixel (x, y) |
Outline Points count screen pixels relative to the canvas corner. Each endpoint is clipped to its canvas width and height before its screen position is added. On a multicolor canvas every x must be proved even, including later replacements of remembered Points; the last horizontal position is the left pixel of the final pair. Source Point lists and histories keep their local screen-pixel coordinates.
Canvas pixels
Each pixel holds a Color or a case from a simple enum whose associated value type is Color. Either can be optional. nil reveals earlier drawings and, below them, the canvas background.
enum Lamp: Color
case glow = .red, lava = .orange, core = .yellow
end
var field: [42 of [32 of Lamp?]] = nil
const picture = System.screen.canvas(multicolor: true)
picture.background <- .black
picture.drawings <- [pixels(field, x: 96, y: 16, size: 4)]
when start
field[20][16] = .core
end
when System.keyboard.space.pressed
Lamp.core = .white
endThe field stores names. Reassigning Lamp.core recolors every core pixel without rewriting the bitmap, scanning the field or restarting work that calculates those names. Equal colors skip display stores. A theme finishes within one refresh, either in the border or in row order behind the beam. The compiler includes both multicolor memory planes and refuses a color footprint whose complete update cannot fit.
| Canvas | Color enum limit |
|---|---|
| Hires | Two non-optional cases, or one optional case plus absence |
| Multicolor | The canvas background plus at most three cases |
These limits count declared cases even if some are unused or currently have equal colors. Color enum lists use packed storage: this 42-by-32 optional field takes 336 bytes, including absence. Copies, work results and retained requests each count toward memory while they are live. Two drawings using the same enum share its colors. Drawings sharing a color cell need a compatible composition proof; the compiler suggests a shared enum or free Color rows when it cannot prove the mixture. Keep unrelated strokes and pictures in separate color cells when their colors are independent.
Pixel dimensions are positive compile-time whole numbers. Positions count from the canvas's top-left corner. Sample [row][col] paints the rectangle starting at (x + col * pixel_width, y + row * pixel_height). The entire rectangle must fit: the compiler refuses known failures and checks changing positions before accepting them. It never clips or rounds a pixel grid. Empty rows or columns draw nothing. Multicolor needs an even x and pixel width; use column * 2 for a changing horizontal position. Native pixels are 1-by-1 in hires and 2-by-1 in multicolor.
Free Color rows preserve exact requested colors. A hires cell admits any two colors across its 8-by-8 pixels. A multicolor cell admits its background plus three other colors across its four double-width pixels and eight rows. The runtime prepares changing candidates privately and checks every affected cell before drawing any of them. It keeps matching accepted color assignments and fills the remaining choices in a stable order. A fixed free-color image can become an ordinary native picture without retaining a redundant source grid.
This small brush changes one painted square. Its empty neighbors reveal black, so each affected hires cell still uses only two colors:
var paint: [8 of [8 of Color?]] = nil
const sketch = System.screen.canvas()
sketch.background <- .black
sketch.drawings <- [pixels(paint, x: 32, y: 24, size: 2)]
when start
paint[1][1] = .orange
end
when System.keyboard.space.pressed
paint[1][1] = .purple
endIf the last cell fails, the previous picture stays visible. The Lab reports the source line, zero-based cell row and column, requested colors and capacity below the picture. Earlier state assignments keep their ordinary effects. The runtime does not substitute colors or roll state back.
A screen interrupt can set a fixed multicolor background split with picture.background = .blue. The store takes effect below that interrupt's line; the base binding restores the background before the next picture. A crossing cell may use both row backgrounds, but its remaining colors must fit the same three choices across all eight rows. Conditional or changing split schedules need a complete row and timing proof and are refused when that proof is unavailable.
Direct writes to drawn enum colors include their display stores when the compiler checks a frame handler's .deadline(line:) or a screen interrupt's timing. When a screen interrupt changes these colors, the compiler refuses competing foreground reads and writes, updates from another interrupt, and timer changes. A helper using mut retains those restrictions. Changing an upstream theme number does not move a later binding into the handler.
Pixel repair retains immutable requests, painter order, old and new coverage and the canvas's presentation checks. picture.shown waits until validation, pixels, colors, other drawing engines and newer requests have settled at a frame opening. Partial canvases still need complete rows drawn together; changing pixel pictures inside cases need a proved whole-picture update and receive a refusal when that path is unavailable. Recoloring alone does not make separate pixel edits appear all at once.
The Lava lamp example calculates one whole image in ordinary work: image: LampPixels? <- blobs.image(), and draws it directly with pixels(image ?? blank, ...). Its completion handler moves the blobs for the next calculation. The compiler can share a private bound result with pixels, holding the worker while row capture and final verification use it. Painting reads its separate accepted snapshot while later work can continue. Both captured revisions remain separate; other readers keep ordinary value copies. Dirty rows skip repainting, and a theme changes both color planes inside the border without recalculating heat. The maintained observation completes pictures about every 8 PAL or 10 NTSC refreshes in an 8,856-byte program. This measured trajectory is not a deadline for every future pose or theme.
Outlines and paths
Lines, open paths and circles also accept .inverted. Open paths may bind the whole drawing list as paths.lines() when paths is a fixed list or history of Point lists. Each drawing slot keeps the same kind of stroke and Point count across its choices.
Whole paths in that fixed list may be optional. A nil path draws nothing and erases its previous pixels while preserving overlapping paths; it keeps its place in the list. All declared slots and Points still count toward storage and work limits, even when every path is nil. Individual Points cannot be nil. Unwrap each optional value from a history before drawing it; optional whole-path bulk lists use .lines(), not .outline().
const canvas = System.screen.canvas()
type Path = [3 of Point]
const path: Path = [(x: 16, y: 16), (x: 64, y: 16), (x: 64, y: 48)]
var paths: [2 of Path?] = [path, nil]
canvas.drawings <- paths.lines()Circles count screen pixels, including on multicolor canvases: x and radius must be even there. The midpoint pixels map to horizontal pairs, with each visible pair toggled once by an inverted circle. Radius zero draws one pixel. The center and radius may change; the complete circle must stay inside the canvas, with a runtime check when the type ranges cannot prove this.
const canvas = System.screen.canvas()
const path: [3 of Point] = [(x: 16, y: 16), (x: 64, y: 16), (x: 64, y: 48)]
canvas.drawings <- [
line(from: (x: 80, y: 20), to: (x: 120, y: 60)),
path.lines(),
circle(x: 160, y: 100, radius: 24).inverted,
]Drawing functions may keep pixel geometry in local const values and return a whole conditional list (if open then [a, b] else nil end), or choose equal-length lists. A slot can use match or place a member of a constant Picture list (pictures[index].place(x:, y:)). Each alternative retains the canvas's bounds and resource checks.
Both place and fill also accept flip: .horizontal or flip: .vertical to mirror the picture left-to-right or upside-down without storing a second copy of the art.
const picture = System.screen.canvas()
picture.color <- .black
picture.background <- .white
const corner = Picture(["XXXXXXXX", "X.......", "X.......", "X......."])
show <- System.joystick[2].fire
const box: [3 of Point] = [(x: 200, y: 20), (x: 300, y: 30), (x: 250, y: 90)]
picture.drawings <- [
corner.place(x: 32, y: 32),
corner.place(x: 64, y: 32, flip: .horizontal),
Text("SCORE").place(x: 16, y: 8),
if show then box.outline().inverted() else nil end,
]For Text(content).font(face).place(x:, y:) on a canvas, the content is a string literal of 1 to 40 characters written right in the program. If you omit .font(...), it uses Font.uppercase; you can also pass Font.lowercase or a custom Font(file:) loaded from your project folder. The letters take the canvas's color, so .ink(...) does not apply to them yet, and .at(...), .width(...) and the other words of a placed text belong to the text screen: a canvas places its letters with place. On a multicolor canvas, the font must also be created with multicolor: true.
Where a Drawing May Go
Inside a canvas, x counts pixels from the left edge and y counts pixel rows from the top. Every drawing must stay completely inside its canvas: for example, a 24-pixel-wide picture on a 320-pixel-wide canvas needs x between 0 and 296. If the compiler can see at build time that a coordinate is always out of bounds, it catches the mistake right away with placeRange. When the declared ranges of your x and y variables already prove that the drawing can never step off the canvas, the compiler emits zero bounds-checking code. If a variable's type is wider than the safe span (say, Number<u16>), the compiler inserts a tiny run-time bounds check that halts on that line if the drawing would ever leave the canvas—and the cost report notes both the check and how to narrow the variable's range (like x: Number<0...296>) to make the check disappear.
In video memory, each byte of a canvas holds 8 horizontal pixels. Whenever the compiler can prove from your expression that x lands on an 8-pixel byte boundary—such as a constant multiple of 8 or column * 8—it takes a fast byte-aligned path that copies bytes straight into the bitmap without shifting. For arbitrary pixel positions, it automatically pre-shifts or masks the art, and the cost report tells you which path each drawing line uses. On a multicolor canvas, pixels come in pairs, so x must be provably even (such as an even constant or column * 2). If a .fill(...) starts or ends partway through a byte, its width must be a compile-time constant so the edge masks are fixed (placeShifted).
When a Picture carries its own cell colors—such as Picture(art, color: .red) or a multicolor picture with palette colors—stamping it also colors the 8-by-8 character cells underneath, so its vertical position y must be a multiple of 8 (placeCells).
Drawing Over Frames
You never have to manually erase old positions or flip double buffers on a canvas: Adder tracks what moved or changed and chooses how to repair the picture. When a drawing moves or turns nil, the runtime automatically repairs the uncovered area from any drawings sitting underneath it, and clears any pixels no longer touched by any drawing. When every line on a hires canvas moves, Adder compares the cost of clearing the old area once with erasing the old lines, including the work to draw the next picture. It chooses clearing when that costs less, for small drawings as well as large ones. Short lines spread far apart can cost less to erase individually. Unchanged lines and inverted overlays keep their usual updates. Pictures, pixel fields, printing, partial canvases and canvases inside cases keep their existing updates. If a big case change or a large .fill(...) needs more cycles than a single frame can spare, the canvas renderer works incrementally across a few frames, pausing cleanly each frame so your handlers and sound never miss a beat.
The picture.shown event fires at the start of every frame in which the canvas is completely caught up—with no incremental drawing left in flight and no new changes pending. Updating your drawing positions inside when picture.shown lets an animation step forward as fast as the bitmap renderer can complete each frame:
const picture = System.screen.canvas()
const badge = Picture(["XXXXXXXX", "X......X", "X......X", "XXXXXXXX"])
var x: Number<0...304> = 0
when picture.shown
x = if x == 296 then 0 else x + 8 end
end
picture.drawings <- [badge.place(x: x, y: 40)]The Wireframe example binds 24 edges with picture.drawings <- turns[turn].lines() and advances turn on picture.shown. Its measured complete 32-picture turn averages 6.00 PAL or 7.06 NTSC refreshes per picture, including capture, drawing and completion. A maintained hand-written assembly reference draws the same poses into two alternating bitmaps and erases only the bytes each bitmap last used. It measures 4.81 PAL and 5.00 NTSC refreshes per picture, including recording those bytes and switching the visible picture. Adder takes 1.247 times its PAL cycles and 1.413 times its NTSC cycles; the scoreboard holds both below 1.5. These trajectory measurements are not deadlines for other shapes. Clearing adds 418 file bytes and 442 resident bytes to this example compared with erasing each line; Adder keeps individual erasure when the added storage cannot fit.
Sprites
The VIC-II video chip gives you eight independent hardware sprites—movable 24-by-21 pixel objects that float over text and bitmap canvases alike without disturbing a single byte of screen memory. System.screen.sprite is the list of all eight, numbered 0 through 7 (with sprite 0 drawn in front of sprite 1, and so on), and each slot takes a Sprite value.
| Field | Type | When left out |
|---|---|---|
x | Number<-24...487> | required |
y | Number<-50...205> | required |
shown | bool | true |
behind | bool | false |
x_expand | bool | false |
y_expand | bool | false |
shape | Shape | Shape.square, a filled square |
color | Color | .white |
Adder translates the video chip's raw hardware offsets for you so that (x: 0, y: 0) places the top-left corner of the sprite right at the top-left pixel of the 320-by-200 picture window. Because a standard sprite is 24 pixels wide and 21 pixels tall, keeping x in 0...296 and y in 0...179 keeps the whole sprite inside the main window, while negative coordinates let you slide a sprite smoothly in from the left or top border. Any sprite you do not bind stays switched off. Set behind: true to put a sprite behind text foreground pixels while leaving it in front of background pixels. In hires text, a glyph's set pixels are foreground. In multicolor text, the second shared color and the cell's own color are foreground; the background and first shared color stay behind the sprite. The priority changes at the frame border with the other sprite fields. Set x_expand: true to stretch a sprite horizontally to 48 pixels wide, and y_expand: true to stretch it vertically to 42 pixels tall.
bat: Number<0...296> <- (System.joystick[2].dx * 4).sum(from: 136)
blink <- System.screen.frame.every(25).toggle()
System.screen.sprite[0] <- (x: bat, y: 170)
System.screen.sprite[1] <- (x: 40, y: 40, shown: blink, color: .yellow)When you give a sprite a multicolor shape, its X pixels use that sprite's own color, while its A and B pixels use the two shared sprite multicolor registers set on System.screen.sprite_multicolor.
Each sprite also reports physical collisions:
System.screen.sprite[n].hit_spritereadstruewhen spritentouched another sprite during the frame.System.screen.sprite[n].hit_backgroundreadstruewhen spritentouched non-transparent background pixels during the frame.
Both collision readings latch once at the start of each frame so testing several sprites stays coherent.
To check whether two sprites intersect in software without waiting for hardware collision latches, call sprite.overlaps(other: Sprite): bool. It calculates whether the two rectangular bounds overlap, accounting for each sprite's shown, x_expand, and y_expand settings.
Sprites as a List
Instead of writing eight separate bindings, you can bind a constant range of sprites—such as System.screen.sprite[0..<4]—to a list of matching length, or bind System.screen.sprite itself to a list of all eight. Each hardware sprite takes the corresponding element from the list, and if the list holds optional Sprite? values, any slot that evaluates to nil switches that sprite off for the frame.
var xs: [4 of Number<0...296>] = [10, 70, 130, 190]
when System.joystick[2].fire.pressed
xs[0] = xs[0] +% 8
end
System.screen.sprite[0..<4] <- xs |> map(fn(x) -> Sprite(x: x, y: 50, color: .yellow))Because each hardware sprite maps to specific VIC-II registers, the index or range in System.screen.sprite[...] must be a compile-time constant within 0...7 (spriteIndex). Each sprite can be bound only once at a given scope and publication row—whether individually or as part of a slice—so the compiler catches duplicate bindings with spriteBoundTwice and mismatched list lengths with spriteListLength. When you build a sprite list with map(xs, transform), the compiler normally emits one compact loop that updates the sprites in turn; putting fast before the binding unrolls it into direct stores to each sprite's registers, spending a few extra bytes to shave off cycles.
Sprites at a Raster Row
Add on System.screen.interrupt(line:) to show a complete sprite or a fixed sprite list at a fixed picture row. A later row can reuse a slot after its earlier sprite finishes drawing, so a picture can contain more than eight sprites.
System.screen.sprite[0..<2] on System.screen.interrupt(line: -11) <- [
Sprite(x: 120, y: 80, shape: Shape.square, color: .yellow),
Sprite(x: 180, y: 120, shape: Shape.square, color: .white)
]
System.screen.sprite[0] on System.screen.interrupt(line: 109) <- (x: 180, y: 140, shape: Shape.square, color: .white)The compiler prepares each complete value and its shape before the display period. Every row uses that same completed view, together with the terrain's screen choice and fine scroll. Changing foreground state between rows cannot change a later sprite early. The row selects publication time; the sprite's x and y still count from the picture's top-left.
Build a fixed-size formation with map, a bounded loop or a helper returning Sprite, just as you would build an ordinary list. The compiler keeps proved positions and fixed attributes through these calculations. Preparing and copying the list still counts toward the frame's work.
The compiler checks every pointer, color, attribute and position store before the first fetch, and counts all uses against the frame on PAL, NTSC and early NTSC. It includes vertical expansion when deciding whether an earlier use has finished. A refused reuse names both source lines and picture rows. Move the service earlier, move its sprite lower, or narrow its Y range when the compiler cannot prove a window.
Use program-level bindings in one text display, give every sprite binding in that program a raster row, and keep each complete use above picture row 205. Keep shared palettes, background colors and display modes fixed for this service. Separate interrupt handlers cannot change these shared colors. Changing terrain must have a proved completed screen view; a text presenter that finishes separately is refused. Mapped memory, assembly, timer interrupts, elapsed clocks and device transfers retain refusals when their interference cannot be proved. Individual field bindings and complete sprite assignments inside an interrupt do not use this service.
Physical collision readings still name slots: when a slot serves two sprites, its collision bits can describe either use. The Raster flight example flies two formations of seven aircraft over a scrolling city with seven slots.
The Keyboard
System.keyboard lets you test individual keys as live switches, process a buffered queue of typed keystrokes, or let the player type and edit a full input line:
| Member | Kind | Type |
|---|---|---|
a key name, such as space or a | reading | bool, true while the key is held down |
[k], where k is a Key | reading | bool, for a key chosen dynamically while the program runs |
stroke | event | Event of Keystroke |
dropped | event | Event |
line | reading | String<n>, where n is the configured capacity |
line.capacity | output | a constant from 0 to 255 |
line.entered | event | Event of String<n> |
caret | reading | Number<0...n> |
All 64 key names on the Commodore keyboard matrix are listed in Named Sets.
Keys
Every key on the keyboard is a boolean reading that stays true for as long as the player holds that key down. Tack on .pressed to get an event that fires in the single frame the key goes down, or .released for the frame it springs back up.
var lives: Number<0...3> = 3
when System.keyboard.space.pressed
lives = lives -| 1
end
System.screen.border <- if System.keyboard.left_shift then .red else .black end
System.screen.text[0][0..<1] <- lives.digits(1)Want customizable game controls where the player can rebind which key jumps or fires? System.keyboard[k] tests a key chosen at run time from a variable, parameter, or list element of type Key. If you already know the exact key when writing the line, write it as a member (System.keyboard.a) rather than in brackets (keyLiteral).
var k: Key = .a
when System.keyboard.space.pressed
k = .z
end
System.screen.border <- if System.keyboard[k] then .red else .black endBehind the cases, the compiler is thrifty with the keyboard matrix: if your program checks only a few fixed keys, it probes just those matrix columns, and if you read enough keys (or index dynamically with [k]) that a full matrix scan is cheaper, it automatically switches to scanning the whole keyboard once per frame.
Keyboard readings come from a matrix of switches that shares its lines with both joystick ports. Some simultaneous controls can make an unpressed key appear held or hide a real press; .pressed, .released and typed keystrokes depend on those sampled readings.
Keystrokes
When you are building a text adventure, a high-score initials screen, or a menu shortcut handler, System.keyboard.stroke gives you a stream of typed Keystroke values—one event for each key press, including key repeat when a key is held down. Each Keystroke carries key (the Key that was pressed), boolean flags for shift, control, and commodore, and a repeat flag telling you whether the stroke came from auto-repeat. Calling s.character() on a stroke returns its printable Char (with shift already applied), or nil for non-printing keys like the cursor arrows, function keys, RETURN, or DEL.
var shown: Char = .space
when s = System.keyboard.stroke
if c = s.character() then
shown = c
end
end
System.screen.text[12][20] <- shownThe runtime buffers up to ten keystrokes in order so fast typists do not lose letters across busy frames. If ten strokes are already waiting in the queue and an eleventh arrives before your handlers consume them, System.keyboard.dropped fires in that frame so your program knows the buffer overflowed.
The Typed Line
For prompts where the player types a name or a command and hits RETURN, System.keyboard.line handles the editing for you. First, bind System.keyboard.line.capacity <- n to a constant capacity from 0 to 255. Reading the line without a capacity reports keyboardLineCapacity. line holds a String<n> with a separate logical length; its cursor position, keyboard.caret, ranges from 0 to n. Moving the cursor alone leaves length unchanged. A printable character overwrites at the cursor and extends length when needed; moving beyond the live end fills the intervening gap with spaces when the next character is typed. Control/Commodore strokes do not insert characters. A full line drops further characters at its end.
DEL moves left and removes that live character, shifting only the live suffix. Shift-DEL inserts a space and shifts right, dropping the final character when full. HOME moves to zero; Shift-HOME clears the logical line. Trailing spaces are content, including when the cursor is elsewhere.
The default editing mode is overwrite: typing in the middle replaces that character. To make room first, press INST (Shift-DEL) once for each space you need, then type over those spaces. Moving beyond the live end does not add spaces until an edit needs them.
RETURN fires line.entered with one saved String<n> snapshot shared by every reader, then resets length and cursor. Saved values and deferred Text captures retain that submitted prefix across later input. Capacity zero still submits an empty String. Spare bytes are private; no capacity-wide clear is needed. Bind line directly to a screen slice at least as wide as its capacity, or give an ASCII list destination a fixed [N of Char] type to fill its remaining places with spaces.
const keyboard = System.keyboard
keyboard.line.capacity <- 24
var sent: Number<0...99> = 0
when message = keyboard.line.entered
sent = sent +| 1
end
System.screen.content <- [
Text(keyboard.line).at(row: 2, col: 2).width(8).height(3).wrapped(.word),
Text(sent.digits(2)).at(row: 10, col: 2),
]
System.screen.text[0][0..<2] <- keyboard.caret.digits(2)Setting line.capacity <- 0 admits only empty submitted strings. keyboard.line does not draw to the screen on its own. Display it by binding it into System.screen.text or a placed Text(...).
Showing the input cursor
Add .cursor(.flashing) or .cursor(.steady) to the text where the player edits. Omitting it, or writing .cursor(.hidden), draws no cursor. You do not need a separate cursor variable or a handler to draw it:
const keyboard = System.keyboard
keyboard.line.capacity <- 23
System.screen.font <- Font.lowercase
System.screen.content <- Text(keyboard.line).at(row: 2, col: 2).width(8).height(3).wrapped(.character).cursor(.flashing)This box has 24 cells and room for 23 typed characters, so the cursor still has a cell when the line is full. The cursor reverses the glyph at keyboard.caret, including a space beyond the live end, using that cell's foreground color. A later Text placement paints over it in the usual list order. Another view of the same line shows no cursor unless it also takes .cursor(...).
A flashing cursor starts shown and alternates every half second: 25 display frames on PAL, 30 on NTSC. Each delivered keystroke shows it again and restarts the half second. A steady cursor stays shown wherever its index has a cell. A move between rows restores the old row and draws the new one through the normal redraw budget; those complete rows can appear on different refreshes. RETURN and Shift-HOME leave the empty input ready at index zero; the new cursor remains there while the old reversed cell is restored.
The view determines which positions have cells:
| View | Cursor position |
|---|---|
label without .width | col + caret, hidden past the screen's right edge |
| clipped row | col + caret, hidden when caret >= width |
| character-wrapped box | row row + caret / width, column col + caret % width, hidden below height |
The index can move past the live end up to the line's capacity. It can also leave the visible box: the cursor then hides, and editing and RETURN still work. There is no automatic scrolling. If capacity equals the number of visible cells, a full line's end index has no cell; reserve one extra visible cell when you want the end cursor to stay visible. Capacity zero never shows a cursor and still submits an empty String.
A cursor needs a constant row and col in .at(...), the keyboard line itself or a pure name bound to it, and a direct binding to System.screen.content. It supports labels, clipped rows and character-wrapped boxes with the machine's uppercase or lowercase font. Word wrapping, hyphenation, alignment, justification, custom or changing fonts, bitmap and other text modes are refused. Previews without cursors can still use word wrapping or other layouts.
Several one-row views with a cursor may have different widths. If a multi-row wrapped view has a cursor, every view with a cursor must use the same width and height, so vertical movement follows one box; do not mix it with one-row views that have a cursor. Other previews can have any size when they omit .cursor.
Editing keys
The Commodore keyboard has two physical cursor keys. Each has two directions: hold either Shift key to use its second direction. Cursor movement does not change the line's length. Down and up move by the width of the character-wrapped cursor box; down reaches a partial last row by clamping to capacity and stops on the last row, while up stops on the first row. Labels, clipped rows and views without a cursor ignore down and up.
| Commodore key | Effect on the typed line | Browser keyboard or on-screen key |
|---|---|---|
| cursor-right | move right, up to capacity | on-screen CRSR → |
| Shift + cursor-right | move left, down to zero | on-screen CRSR ← |
| cursor-down | move one box row down | on-screen CRSR ↓ |
| Shift + cursor-down | move one box row up | on-screen CRSR ↑ |
DEL | move left and remove that live character | Backspace or Delete |
INST (Shift + DEL) | insert one space, dropping the last character if full | Insert, or Shift + Backspace/Delete |
HOME | move to index zero | Home |
CLR (Shift + HOME) | clear the line and move to zero | Shift + Home |
RETURN | submit the complete live line and reset to zero | Enter |
Control and Commodore do not alter these editing keys, and they suppress printable-character insertion. Held keys repeat after 19 frames, then every four frames. Turn on Cursor keys below the Lab screen or in the VS Code emulator toolbar to edit with host arrows; on-screen CRSR keys always work. With Cursor keys off, host arrows retain their usual joystick controls.
Joysticks
System.joystick[1] and System.joystick[2] read standard digital joysticks plugged into control ports 1 and 2.
| Member | Kind | Type |
|---|---|---|
dx | reading | Number<-1...1>: -1 left, 0 centered, 1 right |
dy | reading | Number<-1...1>: -1 up, 0 centered, 1 down |
fire | reading | bool, true while the fire button is held down |
Just like a keyboard key, fire.pressed fires in the frame the button goes down, and fire.released fires in the frame it is let go.
x: Number<0...296> <- (System.joystick[2].dx * 2).sum(from: 136)
y: Number<0...179> <- (System.joystick[2].dy * 2).sum(from: 80)
var shots: Number<0...99> = 0
when System.joystick[2].fire.pressed
shots = shots +| 1
end
System.screen.sprite[0] <- (x: x, y: y)
System.screen.text[0][0..<2] <- shots.digits(2)Both control ports share keyboard wiring: port 1 uses row lines and port 2 uses column lines. A joystick can pull a shared line low, and held keys can affect joystick readings too.
When a program reads the keyboard alongside System.joystick[1], Adder deliberately masks any rows that read low with all keyboard columns released. Keys in those rows read as released, so fire hides Space, among others. The cost report notes this masking.
Port 2 avoids that row mask, but simultaneous keys and movement can still produce ambiguous readings. In one host emulator check, Right on port 2 plus 7 made a program choose 1. Its System.keyboard.one.pressed handler came before System.keyboard.seven.pressed; both handlers accepted a choice only while none had been made. The guards and handler order explain the accepted choice; the sampled pins still cannot distinguish some physical combinations. This observation is specific to that program and host check. Choose and test the simultaneous controls your application supports on its target machine.
The Mouse and Paddles
System.mouse reads a Commodore 1351 proportional mouse plugged into control port 1. As soon as your program reads any member of System.mouse, the compiler links in the mouse driver automatically.
| Member | Kind | Type |
|---|---|---|
x | reading | Number<0...319> |
y | reading | Number<0...199> |
left, right | reading | bool, true while that mouse button is held down |
x and y track the pointer's pixel position across the 320-by-200 picture window using the exact same coordinate system as sprites and canvases, and the driver clamps the pointer so it stays on screen. You draw the pointer yourself—most often by binding a sprite's x and y straight to mouse.x and mouse.y.
const mouse = System.mouse
var clicks: Number<0...99> = 0
when mouse.left.pressed
clicks = clicks +| 1
end
System.screen.sprite[0] <- (x: mouse.x, y: mouse.y)
System.screen.text[0][0..<2] <- clicks.digits(2)System.paddle[1] and System.paddle[2] read a pair of analog game paddles plugged into control port 1. Turning a paddle dial gives you a smooth Number<u8> reading from 0 at one end of the dial to 255 at the other.
x: Number<0...296> <- System.paddle[1] + 20
System.screen.sprite[0] <- (x: x, y: 170)Control Port 1
Because joystick 1, the 1351 mouse, and the paddle pair all plug into the same nine-pin socket on control port 1, only one of those three device kinds can be wired up at a time. The two paddles share a single Y-cable plug and count as one device, so a two-player paddle game can read both System.paddle[1] and System.paddle[2] together. If a program tries to mix two different port-1 devices (say, reading both System.mouse and System.joystick[1]), the compiler catches the conflict with controlPortOne.
Sound
System.sound[1] is the machine's famed three-voice synthesizer chip (the SID), and its three voices—voice[1], voice[2], and voice[3]—can each play an independent musical note or sound effect at the same time. You can drive a voice in either of two styles: bind it continuously to a Tone with <-, or trigger notes imperatively with play and release inside when handlers.
In addition to individual voice controls, System.sound[1] provides chip-wide volume, analog filtering, and direct voice 3 hardware readings:
System.sound[1].volume: an output of typeNumber<0...15>setting the master volume (defaults to 15).System.sound[1].filter: an output takingFilter(cutoff: 0...2047, resonance: 0...15, low_pass: bool, band_pass: bool, high_pass: bool, mute_voice_3: bool)configuring the SID analog filter. Voices whose bound tones specifyfiltered: trueare routed through this filter.System.sound[1].voice[3].oscillator: an 8-bit volatile hardware reading ($D41B) reflecting the voice 3 waveform output, useful for digital random numbers or drawing audio waveforms.System.sound[1].voice[3].envelope: an 8-bit volatile hardware reading ($D41C) reflecting the voice 3 envelope level, useful for visualizers.
Tone
A Tone bundles pitch with timbre, modulation, and volume envelope:
| Argument | Type | Meaning |
|---|---|---|
| first / pitch | Note | the musical pitch, such as .c4 or .f_sharp3 |
frequency | Number<u16> | explicit 16-bit SID frequency |
hz | Number | physical frequency in Hertz |
detune | Number<i8> | pitch offset from -128 to 127 |
waveform | Waveform | .triangle (default), .sawtooth, .square / .pulse, .noise, or a combination waveform |
pulse_width | Number<0...4095> | pulse duty cycle (default 2048) |
ring | bool | ring modulation with preceding voice |
sync | bool | oscillator hard sync with preceding voice |
gate | bool | gate control (default true) |
test | bool | oscillator test bit to reset waveform cycle |
filtered | bool | route voice output through the chip filter |
attack | Number<0...15> or Attack | attack rate (0 is fastest 2 ms hardware rate) |
decay | Number<0...15> or Decay | decay rate |
sustain | Number<0...15> or Sustain | sustain volume level |
release | Number<0...15> or Release | release rate |
envelope | Envelope | full ADSR envelope struct |
Envelope(attack:, decay:, sustain:, release:) takes the distinct Attack, Decay, Sustain, and Release selector types, each from 0 to 15. Write their constructors, such as Attack(2) or Sustain(8), or a named selector such as Decay.short. Direct Tone arguments attack:, decay:, sustain:, and release: also accept bare numbers from 0 to 15. Attack ranges from 0 (the fastest 2-millisecond hardware rate) up to 15 (a slow 8-second swell). A Tone specifies either a quick decay: preset, direct ADSR fields, or a full envelope:, never a conflicting combination (toneEnvelopeConflict). Pitch is given as a note, an explicit frequency, or hz (tonePitchConflict).
.silence is the silent Tone value that releases or mutes a bound voice.
Binding a Voice
Binding a voice with <- turns it into a live instrument that tracks your expression: while the binding evaluates to a Tone, the voice sounds that note, and when it evaluates to .silence, the voice releases its gate and fades out. If you do not specify a decay: or envelope: on a bound tone, Adder gives it a clean organ-like sustain envelope (Attack(2), Sustain(15), Release(2)).
held <- System.joystick[2].fire
const tune: [8 of Note?] = [.c4, nil, .e4, .g4, .c5, nil, .g4, .e4]
step: Number<0..<8> <- System.screen.frame.every(12).cycle()
System.sound[1].voice[1] <- if held then Tone(.c4) else .silence end
System.sound[1].voice[2] <- if n = tune[step] then Tone(n, waveform: .square) else .silence endThe runtime touches the SID registers only in frames where the bound Tone actually changes. Sliding from one Note directly to another retunes the pitch smoothly (legato) without re-triggering the envelope, whereas coming back from .silence gates a fresh note. In the cost report, a voice binding takes at most 9 cycles in a quiet frame where the tone stays the same, and 17 cycles in a frame where the tone changes.
If you craft a custom Envelope for a bound voice where the Attack number is smaller than the Release number, your program still compiles, and the cost report attaches a helpful note on that line. It explains that re-gating that voice while its release tail is still audible can trigger the SID chip's 33-millisecond envelope delay, and tells you the exact Attack(...) value that avoids it.
Play and Release
For one-shot sound effects—laser zaps, coin chimes, jump boings—or piano-style key down / key up control, use voice.play(tone) to strike a note and voice.release() to let it fade out over its release rate. Because both are imperative actions, they belong inside when handlers; writing either one outside a handler is flagged with playOutsideOn. When you pass a Tone without an explicit decay: or envelope: to play, it defaults to a percussive struck envelope that rings out and decays on its own without needing a separate release(). To guarantee that every note strikes cleanly even when a voice is already sounding, play resets the SID envelope and gates the new note two frames later; if another play arrives on the same voice during that brief window, the newer note cleanly replaces the pending one.
const ping = Tone(.c6, decay: .short)
const soft = Envelope(attack: Attack(2), decay: Decay(4), sustain: Sustain(8), release: Release(6))
var v: Number<1...3> = 1
when System.keyboard.space.pressed
System.sound[1].voice[v].play(ping)
v = v +% 1
end
when System.keyboard.return.pressed
System.sound[1].voice[1].play(Tone(.c4, envelope: soft))
end
when System.keyboard.return.released
System.sound[1].voice[1].release()
endAs shown above, the voice index in System.sound[1].voice[v].play(...) and .release() can be a runtime variable of type Number<1...3>—handy for round-robin sound effect allocation across all three voices.
Within any given scope, each voice is controlled in one way: either bound with <- or driven by play/release. Mixing a binding and play/release on the same voice in the same scope is flagged with voiceBoundAndCalled, and binding the same voice twice is flagged with voiceBoundTwice. A case, however, can bind a voice that the outer program also binds: while the case is active, the case's binding takes over that voice.
Tracker and Synthesis Techniques
Adder supports classic sound design and tracker techniques:
- Hard restart: Setting a tone with
gate: falseandattack: 0before gating a note drains the voice envelope to silence, preventing note-on clicks and ensuring consistent attack transients. - Oscilloscope and visualizers: Reading
System.sound[1].voice[3].oscillatordirectly inside a frame handler or raster loop lets you draw live audio waves or sample random noise without wasting processor cycles on software waveforms. - In-place ADSR updates: Changing envelope rates on an active tone while
gate: truepreserves the sounding note and updates envelope parameters in place without re-triggering the voice.
The Clock
When you want wall-clock timing that runs at the exact same speed on 50 Hz European PAL machines and 60 Hz North American NTSC machines, System.clock keeps time for you:
| Member | Kind | Type |
|---|---|---|
interval(seconds:) or interval(ms:) | event maker | Event, firing repeatedly once every period |
timer(seconds:) or timer(ms:) | event maker | Event, firing once after the period elapses from program or case start |
hours | reading | Number<0...23> |
minutes, seconds | reading | Number<0...59> |
tenths | reading | Number<0...9> |
Intervals and Timers
You bind an interval or timer to a name with <- and respond to it in a when handler. Each maker takes either seconds: or ms: (never both, and never zero or negative), written as a positive compile-time number; any other period specification is caught with periodicPeriod.
beat <- System.clock.interval(seconds: 0.25)
ready <- System.clock.timer(ms: 1500)
var hue: Number<0...15> = 0
var lit: bool = false
when beat
hue = hue +% 1
end
when ready
lit = true
end
System.screen.border <- Color(hue)
System.screen.background <- if lit then .white else .black endWhether your player is on PAL or NTSC, a quarter-second interval lasts a true quarter of a second: the runtime calibrates the hardware timer in the detected machine's exact clock cycles (rounded up). Inspecting or filtering a clock event never advances or resets its hardware countdown. An interval delivers at most one tick each time the program reads the clock, so its period has to be at least the longest time between two reads. The compiler works that time out from the finished program on PAL, NTSC and early NTSC, and refuses a shorter interval with periodicOwnership, naming the gaps and the fewest whole milliseconds that work. A program that reads the clock once a frame can use interval(ms: 40), 25 ticks a second, on every machine, including one that copies colors; heavy frames, a long when start stretch in the first frame, and raster routines that run beside the frame wait make the gap longer. A frame that spreads a drawing or text over several frames, that ends with a work job result, or that waits for the beam keeps a cautious figure of two screen refreshes, so it needs interval(ms: 41) or longer; the refusal says which of these the frame is. Beside a raster routine, such a frame is refused whatever the interval, because a routine can share a program with a clock only when the compiler can bound the gap. A raster routine that changes which sprites show, or the vertical scroll, cannot share a program with a clock; the compiler refuses the program with periodicOwnership. bun tools/costs.ts prints the figure as the admitted maximum sample gap. A timer fires once, so it keeps any delay, however short.
Intervals and timers use CIA 2's timer A: its counter ($DD04–$DD05), control register ($DD0E) and interrupt mask and flags ($DD0D), through every 16-byte mirror up to $DDFF. They cannot share a program with an asm block, a System.clock.interrupt routine, color bands, or a hardware mapping of those registers; the compiler flags each one where it stands with periodicOwnership. Other CIA 2 registers, such as the video memory port at $DD00, stay available under their usual rules.
A System.screen.interrupt(line:) routine can share the program with a clock:
beat <- System.clock.interval(ms: 40)
var ticks: Number<u16> = 0
when beat
ticks = ticks +% 1
end
when System.screen.interrupt(line: 24)
System.screen.border = Color.red
end
System.screen.background <- Color(ticks % 16)The compiler adds the routine's time to the gap and checks that the clock is still read correctly while the routine runs. It refuses the program at the routine when the routine could hold the processor across the frame wait, or at the interval when the gap grows past its period. This checks the compiler's timing bounds; it does not qualify a whole game or the physical machine.
Interrupt Routines
What if you need a timer that fires faster than once per frame, or right in the middle of the screen? System.clock.interrupt(ms:) and System.clock.interrupt(seconds:) fire repeatedly on a hardware timer just like interval, except their when handler holds a checked interrupt body that runs immediately—between two instructions of your main program—instead of waiting for the next frame boundary. Likewise, System.screen.interrupt(line:) runs a checked interrupt body the instant the video beam reaches a fixed picture row from -51 to 210 on every standard. Interrupt Routines describes both in detail.
Time of Day
hours, minutes, seconds, and tenths read the CIA chip's built-in time-of-day clock, which ticks steadily forward in tenths of a second from the start of the run. Whenever your program reads any of these four members, the runtime latches all four together once at the start of the frame—so minutes and seconds never roll over out of sync mid-frame.
System.screen.text[0][0..<2] <- System.clock.minutes.digits(2)
System.screen.text[0][3..<5] <- System.clock.seconds.digits(2)
System.screen.text[0][6..<7] <- System.clock.tenths.digits(1)In the cost report, a line that formats and displays System.clock.seconds.digits(2) takes 65 bytes and at most 204 cycles per frame.
Disk Drives: System.drive[8...11]
The serial IEC bus connects up to four floppy disk drives, numbered 8 through 11 (with 8 being the primary boot drive). Adder provides high-level persistent serialization and sequential file streams directly on System.drive[d]:
| Member | Kind | Description |
|---|---|---|
load(name, attempt:) | reading | Loads a serialized value reactively; evaluates to Result of T? |
save(name, value) | action | Serializes and saves value to name; returns Job of Result of Receipt |
file(name) | maker | Accesses sequential file stream operations on name |
file(name).read(capacity:) | reading / stream | Streams bytes sequentially with buffer capacity 1...255 |
file(name).write(data) | action | Overwrites or creates a sequential file; returns Job of Result of Receipt |
file(name).append(data) | action | Appends bytes to a sequential file; returns Job of Result of Receipt |
Reactive Loading and Disk Swapping
System.drive[d].load(name, attempt:) loads structured state into a reactive Result of T? binding. While reading bytes over the serial IEC bus across frames, the binding evaluates to nil. Once the complete payload is read and validated, it evaluates to .success(value) or .failure(reason).
Changing the filename starts a fresh read without needing to change attempt:. Keeping the same drive, filename and attempt keeps the completed result.
The optional attempt: parameter enables disk swapping and retry loops: incrementing or altering attempt cancels any in-flight transfer and initiates a fresh read from the drive:
var attempt: Number<u8> = 0
val: Result of Number<u8>? <- System.drive[8].load("savegame", attempt: attempt)
when System.keyboard.space.pressed
attempt = attempt +% 1
end
System.screen.border <- match val
nil -> .yellow
success(value) -> .green
failure(reason) -> match reason
damaged -> .orange
wrong_type -> .purple
else -> .red
end
endEvery saved value includes an "AD" magic header followed by a 16-bit type hash computed from the value's structural type. Adder returns .damaged for truncated, corrupt or impossible contents and .wrong_type for a complete valid header with a different type hash. A failed load gives no value. The drive's own errors keep .device_error(code:); code 74 means the drive is not ready. Each reason has a 40-character message you can show on screen.
Loading art
An art load uses the same pending and failure states as a saved value. Declare the art as usual, then load its generated companion:
const world = Font([Glyph([129,66,36,24,24,36,66,129])])
art: Result of Font? <- System.drive[8].load("world.chr")
System.screen.font <- match art
nil -> Font.uppercase
success(font) -> font
failure(reason) -> Font.uppercase
endYou can give the selected font a name with an ordinary binding, then use that binding in another if or match when choosing System.screen.font.
With an art load present, Adder packages top-level custom font declarations as name.chr and shape or fixed shape-list declarations as name.shp. Use an ASCII declaration name of at most 12 characters, leaving room for the four-character extension. For example, const ships: [12 of Shape] = ... supplies ships.shp, loaded into Result of [12 of Shape]?. A single shape uses Result of Shape?.
The program reserves fixed reading and display storage for each load. Further levels stay in companion files. After reading and checking the file, Adder copies one font page or one shape per update into inactive native slots. The binding stays nil until the complete set is ready. Changing the filename or attempt: restarts this work. Damaged data leaves the preceding native set intact, and the load returns the existing named failure.
Use the binding's latest successful art. A later success from the same load may reuse earlier native slots; use separate loads when two sets must remain available together. Existing art handle and display memory limits still apply.
The CLI writes generated companions beside a standalone program. Disk and cartridge exports include them automatically; the Lab and extension also mount them when you run the program. Magic Desk and EasyFlash read them through drive 8. Keep generated font companions with their compiled program, since their checked type includes that program's character maps.
Generated companions contain typed data, while Font(file:) reads raw project art. Keep their flat filenames distinct: const world = Font(file: "assets/world.bin") supplies the typed companion world.chr. Existing filename collision checks apply.
Open the Art by level example in the Lab to load a tile font and a sentry shape for each of three decks, with a loading state and failure messages on screen.
Saving state
System.drive[d].save(name, value) serializes any serializable type (scalars, structs, enums, fixed-size arrays and lists that grow) and writes it to the designated drive. A list that grows is saved with its live length, and load gives it back with the same items; a file that claims more items than the list's capacity fails with .damaged. The operation returns a Job of Result of Receipt. Its result is optional while work is pending, then reports success with a byte count or a device failure. Disk transfers can pause normal updates while the serial bus is busy:
const score: Number<u8> = 42
const saveJob = System.drive[8].save("player.dat", score)If the disk has a write-protect tab in place, the operation records Failure.write_protected; if the disk sectors are exhausted, it records Failure.disk_full.
To keep a file up to date with a value, bind the save instead. The binding saves the value each time it changes and holds what the drive answered:
var record: Number<u16> = 0
saved: Result of Receipt? <- System.drive[8].save("best", record)A save binding saves nothing at start, so the starting value never replaces a file the program is about to load. It reads nil until the value first changes, then the result of the latest save. Because every change writes the disk, Adder refuses a save binding whose value can change every frame. Save a variable that a handler sets on an event, such as a new best score at the end of a round. Use the handler form for a save that happens once.
File Streams
For custom binary or text protocols, file(name) provides byte streams:
s <- System.drive[8].file("levels.bin").read(capacity: 64)
const appendJob = System.drive[8].file("log.seq").append([10, 20, 30])A stream keeps at most capacity bytes in its transfer buffer. Pass it to another file's write or append to copy a file larger than that buffer. Writing replaces the destination; appending keeps its earlier bytes. The completed receipt counts the bytes transferred by this operation.
var levels = System.drive[8].file("levels.bin").read(capacity: 64)
var copied: Result of Receipt? = nil
when start
copied = System.drive[9].file("levels.bin").write(levels).result
endThe Lab supplies a virtual disk on drive 8 containing the project's non-source companions. Filenames are flat basenames of at most 16 characters; two files whose names shorten to the same name cannot be packaged together. Saved files survive reloading the same project, and snapshots preserve mounted media and open files.
Use the Lab's download-format selector or adder compile project -o game.d64 to export a boot disk. D64 (1541), D71 (1571), and D81 (1581) hold 664, 1,328, and 3,160 data blocks. -o game.crt creates an auto-booting Magic Desk cartridge; add --cartridge easyflash for EasyFlash. Both cartridge types read bundled companions through System.drive[8].load and file(name).read without a floppy. Cartridge assets are read-only; saves and file writes continue to use a disk.
Fixed art in the program may reuse startup memory after Adder unpacks it. This happens automatically when a screen buffer or cleared storage can hold the packed copy; the cost report includes the staging work. Generated art companions keep further sets on the disk or cartridge until a load needs them.
Hardware Registers
For readers who already know their way around the Commodore 64 memory map—or who want to peek under the hood from an asm block—here are the hardware chips and register addresses behind each System device. Normal Adder code never writes raw hex addresses; the System tree handles them all for you.
| Device | Chip | Registers |
|---|---|---|
border, background | VIC-II | $D020, $D021 |
| color bands | VIC-II | raster interrupts through $D012 and $D019–$D01A |
sprite | VIC-II | positions $D000–$D010, shown $D015, multicolor $D01C, colors $D027–$D02E |
text, color, font, canvases | VIC-II | $D011, $D016, $D018, with screen memory and color memory at $D800 |
keyboard, joystick[1], joystick[2] | CIA 1 | $DC00, $DC01 |
paddle[1], paddle[2], mouse | SID | $D419, $D41A, with $DC00 choosing port 1 |
sound[1].voice[n] | SID | voice 1 $D400–$D406, voice 2 $D407–$D40D, voice 3 $D40E–$D414 |
clock.hours to clock.tenths | CIA 1 | time of day $DC08–$DC0B |
clock.interval, clock.timer | CIA 2 | timer A, $DD04–$DD05 |
drive[8...11] | CIA 2 / IEC | serial clock and data lines at $DD00, standard KERNAL IEC vectors $FFBA–$FFCC |
screen.interrupt(line:) | VIC-II | raster compare $D012 and $D011 bit 7, flag $D019, enable $D01A, through the IRQ vector at $FFFE |
clock.interrupt(ms:) | CIA 2 | timer A, $DD04–$DD05, control $DD0E, interrupt mask and flags $DD0D, through the NMI vector at $FFFA |
RAM Expansion Units
The complete source in guide/examples/reu-memory.adder is ready for the CLI or Lab.
System.reu is Reu?: it is nil without a supported RAM expansion unit. Adder checks once at startup, preserving the expansion bytes it probes. An REU can hold 128 KiB through 16 MiB. reu.capacity_kib is read-only, so a program that needs a large terrain image can check its minimum before starting work. Programs that never name System.reu include no REU runtime.
var bytes: [40 of Number<u8>] = 65
var restored: [40 of Number<u8>] = 0
var available: bool = false
when start
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.store(bytes, bank: 16, offset: 0)
reu.fetch(into: mut restored, bank: 16, offset: 0)
available = reu.verify(restored, bank: 16, offset: 0)
end
end
end
System.screen.border <- if available then Color.green else Color.red end| Call | Effect |
|---|---|
reu.store(bytes, bank:, offset:) | Copy a byte list or window into expansion memory. |
reu.fetch(into: mut bytes, bank:, offset:) | Replace a mutable byte list or window from expansion memory. |
reu.fetch(into: mut rows[13..<25], bank:, offset:, stride:, wrap:) | Fill selected rows. Give a stride to space source rows and a range to wrap them. |
reu.swap(into: mut bytes, bank:, offset:) | Exchange those bytes with expansion memory. |
reu.verify(bytes, bank:, offset:) | Return true when every byte matches, or false at the first difference. |
reu.fill(value:, bank:, offset:, count:) | Fill expansion memory with one byte; count is a fixed whole number. |
A list or window of ScreenCode values moves like one of Number<u8>, because a screen code is one byte. A screen row bound to such a list shows what a fetch or swap puts there. Lists of Char, Color, and numbers that are signed, fractional, or not one byte wide are refused rather than read as bytes. The one list of Color a fetch may fill is the screen's own colors, described under Fetching Into the Screen's Colors.
var row: [40 of ScreenCode] = ScreenCode(32)
System.screen.text[12] <- row
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut row, bank: 0, offset: 0)
end
end
endA program that flips between two screens can fetch or swap into the one that is not showing: write screens[1 - front] before the line that changes front, or screens[front] after it. The transfer fills that screen in place, with no copy and no wait for the beam. A transfer into the screen on show, into a screen the compiler cannot tell apart from it, or into a screen whose choice a call can change is copied to the display like any other change to that list, and costs the copy.
var screens: [2 of [25 of [40 of ScreenCode]]] = ScreenCode(32)
var front: Number<0...1> = 0
System.screen.text <- screens[front]
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut screens[1 - front][12], bank: 0, offset: 0)
end
end
front = 1 - front
endFetching Rows
reu.fetch fills a whole fixed matrix or a slice of its rows in one call. The destination contains rows of Number<u8> or ScreenCode, such as [25 of [40 of ScreenCode]]. Its shape gives the row width and count: back[13..<25] selects the last twelve rows of twenty-five.
Optional stride sets the distance in bytes between source row starts. Without it, the source rows lie back to back, each immediately after the previous row. Row k takes its bytes from bank and offset plus k * stride; the first source row always starts at the offset you give, wherever it lands in the destination. A stride of zero repeats one source row, and a stride below the width makes the source rows overlap. A single byte list or a window inside one row takes no stride.
Use optional wrap: first..<end to fetch from a repeating range of REU banks. For example, wrap: 1..<29 uses banks 1 through 28. When the source passes the last byte of bank 28, the next byte comes from the start of bank 1. This also works when a row itself crosses the boundary, and when the destination is the list shown as System.screen.color.
The range is half-open, with a first bank in 0 through 255 and an exclusive end in 1 through 256. It must contain the starting bank and fit in the installed expansion. The call checks these conditions before transferring any byte. A range of one bank wraps within that bank.
var back: [25 of [40 of Number<u8>]] = 0
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut back[0..<13], bank: 0, offset: 0, stride: 512)
reu.fetch(into: mut back[13..<25], bank: 0, offset: 6656, stride: 512)
end
end
endstride is a whole number in 0...65535; a variable has to prove its range, as bank and offset do. The destination selects 1 through 255 fixed-width rows. A slice may start at a changing row, as in back[top..<(top + 12)], but its length stays fixed. An interval outside the destination is a compile error when its bounds already show it, and otherwise a checked failure before any row moves. A row may cross a 64 KiB or a REC 512 KiB boundary of the expansion like any other transfer; it never wraps around the end of the expansion.
Unlike a loop of fetch calls, the whole call is checked before anything moves. The device must be present, the rows must lie inside the destination, and the last byte of the last row must lie inside the expansion, which is a different test from the one the same bytes pass as a single transfer. With a 2 MiB expansion, 25 rows stride: 65535 apart that begin at bank: 8 fail although they move only 1,000 bytes. A call that fails changes nothing: no row, no expansion byte and no REU register. The effects of evaluating its arguments stay, as for any call. Written as separate fetch calls, rows before the first one that does not fit are fetched and kept. The destination and every argument are captured once, in the order written, so a later argument that changes the variable choosing the destination does not move the rows the call writes.
The cost report charges the check once and then every row: its setup, its transfer clocks and the second command of a row that crosses a REC 512 KiB boundary, all of them inside the frame bound. Rows are transfers of their own, so the call is not a single DMA operation, and an interrupt waits for the row in progress, not for the whole call. A row fetch cannot run in a native interrupt handler. Inside a .deadline(line:) handler it follows the rules of a protected fetch: the capacity checked beforehand, addresses that cannot fail, a destination of its own, and a destination slice whose bounds already fit. The capacity check of a protected transfer takes the largest bank and the largest offset that their declared ranges allow, each on its own, so two values that never occur together still count against it; give each variable a tight range. When the rows alone would take too long, prepare them in an ordinary handler and switch to the finished matrix from the deadline handler instead. The deadline handler may fetch bytes of its own, such as color memory, in the same program: it conflicts with the ordinary handler only if the two can write the same bytes, as Completing Before a Picture Row describes. A matrix a screen row is bound to shows the rows the call wrote, and only those.
A row fetch shares the setup between its rows. For the maintained controls with 40-byte rows 512 bytes apart that cannot cross a REC 512 KiB boundary, the cost report gives worst-frame bounds of 254 cycles for a single byte-row fetch and 214 for a slice containing one row. One slice has bounds of 1,839 cycles for 13 rows and 3,399 for 25 rows. These are static bounds, including transfer clocks. A source that can cross a boundary keeps the second command of each row and costs more. The frame bound also charges badlines, sprites and interrupts, so give bank and offset ranges that show where every source row can lie.
Fetching Into the Screen's Colors
A program that binds its colors to a list of its own, System.screen.color <- inks, can fetch into that list. The list is color memory itself. reu.fetch takes the whole matrix, a slice of its rows such as inks[3..<6], one row such as inks[3], or a window inside one row such as inks[3][8..<24].
var inks: [25 of [40 of Color]] = .black
System.screen.color <- inks
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 2048 then
reu.fetch(into: mut inks[0..<25], bank: 2, offset: 0, stride: 512)
end
end
endThe colors a frame fetches show in the next picture, together with that frame's text, scroll and sprites. The call checks its arguments where it stands, and the rows themselves are fetched at the very top of the next frame, in the border, before the screen reads the first of them. The fetch waits for nothing, and the rest of the frame's work is not held up behind the screen. The compiler checks, for every video standard, that each row lands in time with the frame's other work, the sprites and the interrupts counted, and falls back with a reason when it cannot.
A fetch that the frame reads back or changes cannot wait for the next frame. If a later line of the frame reads inks, writes a cell of it, or stores into the bytes of the expansion that the fetch reads, the fetch is made where the call stands instead: the device gets each row's command only after the screen has drawn that row of the picture on show, so the fetch is the last work of the frame, and the cost report names the line that keeps it there. The same goes for a later line that runs assembly, calls library code or uses a name mapped over color memory or the expansion controller's registers, because the compiler cannot see what that code reaches. Reads, stores, assembly and library calls that come before the fetch do not matter. A fetch also stays where the call stands when the frame cannot finish the rows before the screen reads them, because the frame's other work, sprites or interrupts come first, and the cost report says how late the row would be.
Each cell shows the low four bits of its byte, which is all that color memory keeps, and reading the list gives those four bits back. The call is checked whole before the first row, as every row fetch is. The cost report shows how much room the first row has before the screen reads it; for a fetch made behind the screen it says that each write waits for the screen to pass its rows and shows when the last wait ends. The frame check refuses a fetch behind the screen whose last row cannot be written before the picture ends, with the figures. A batch that falls behind the screen counts too: 25 rows behind the screen with eight sprites on do not fit a PAL frame, and 13 rows do.
Only the list bound to System.screen.color can be fetched into this way. These are refused, each with a message that names its cause: any other list of Color; colors chosen among several lists; a list the compiler copies to the screen instead of showing in place (the message names the line that keeps it there); store, verify or swap of the colors, because the upper four bits of color memory read back as noise; a fetch inside a loop; and a fetch in or before a .deadline(line:) handler, because it may have to wait for the screen to draw each row, which a deadline does not count. At start-up, while the display is off, a fetch waits for nothing. A list of Number<u8> placed at $D800 stays the raw way to fill color memory: it is written the moment the call runs, so use the list bound to System.screen.color for writes that wait for the screen.
Preparing a Picture
A program can keep a large map in the expansion and show a window of it that moves. Adder checks this pattern from end to end: two screens that take turns, the rows of the next view fetched into the screen that is not showing, the colors of the same view fetched into the screen's colors, and the flip of the screens in the same frame.
var screens: [2 of [25 of [40 of ScreenCode]]] = ScreenCode(32)
var front: Number<0...1> = 0
var inks: [25 of [40 of Color]] = .black
var row: Number<0...231> = 0
System.screen.text <- screens[front]
System.screen.color <- inks
when System.screen.frame
if reu = System.reu then
if reu.capacity_kib >= 512 then
reu.fetch(into: mut screens[1 - front][0..<25], bank: row / 128, offset: (row % 128) * 512, stride: 512)
reu.fetch(into: mut inks[0..<25], bank: 2 + row / 128, offset: (row % 128) * 512, stride: 512)
end
end
front = 1 - front
row = (row + 1) % 232
endThe rows go straight into the screen that is not showing, with no copy and no wait for the screen. The colors are fetched in the same frame and land at the top of the next one, in the border, before the screen draws any row of them. The next picture therefore shows the new screen, its colors, its scroll and its sprites together, and never a mixture of two views. Each frame shows what the frame before decided. The cost report says where the colors land and how many cycles the first row has before the screen reads it, and the compiler refuses a frame in which any row of the colors could land late.
The REU scroll in the Lab is a complete version of this pattern: a joystick moves a camera over a map of 512 by 256 cells that the program builds in the expansion when it starts, a view is prepared in two batches of rows (13, then 12) while the camera moves, the fine scroll runs in both directions in a window of 38 columns and 24 rows, and a sprite's color follows the view on show. The cost report bounds its frame work at 8,528 cycles or less on every video standard. The compiler decides nothing about the application: which view to prepare, when it is complete and when a newer request drops it are the program's.
The expansion-backed program chooses its preparation schedule. A fixed HUD beside a scrolling region uses the separate bounded admission under Scroll and Window; it does not give an expansion transfer a proved interference window. A font is not a byte list a transfer may fill.
Addresses and Registers
The bank is a byte in 0...255 and the offset a word in 0...65535. A bank contains 65,536 bytes. A transfer uses 1...65535 bytes, inferred from the fixed one-dimensional list or window of Number<u8> or ScreenCode values, or written as fill's count. The complete transfer must fit the discovered capacity; a changing address is checked before any transfer. Adder splits a transfer across a REC 512 KiB boundary so the same source also works with Ultimate's full-carry mode.
Arguments are captured once in written order. Fetch and swap require mut on their destination and preserve ordinary source-order reads and later writes. A store or verify of a window or row of a list the program declares, picked while it runs, such as world[first..<(first + 512)] or grid[row], reads the bytes straight from the list when the transfer runs and copies nothing. Its start is worked out where the argument is written. The compiler copies the bytes first, at that point, when a later argument changes state, when an interrupt routine reads the list or when the list is placed with at, so the transfer always carries the bytes the argument held. Mapped destinations must be ordinary RAM above $01FF or Color RAM, with no I/O boundary crossing. A Color RAM transfer changes only its low nibbles; it does not change the underlying RAM. Noncontiguous columns and native interrupt transfers are refused.
DMA suspends the CPU while the video chip and timers keep running. The cost report charges setup, transfers and conservative display contention; swap needs two transfer clocks per byte. Transfers finish synchronously before the next source statement. They own the REU command, address, count, IRQ mask, fixed-endpoint flags and Ultimate count/delay/rate extension registers. Native assembly remains available for deferred $FF00 triggers, autoload, REU interrupts and other raw register protocols. Physical Ultimate timing is qualified separately from browser and VICE results.
Costs and the Frame
Smooth motion and responsive controls require each frame's work to finish before the television beam starts the next frame. The compiler reports each line's exact byte size and calculates an upper bound on the processor cycles it can take. By default, the compiler proves at build time that every frame's work fits inside a single television frame. If the worst case could run long, it points to the heaviest line. A fast mark tells the compiler where to spend extra bytes to reduce cycles. The cost report shows the tradeoff.
The zero-page line shows how many of the available fast memory cells your program uses and names eligible values that stay in ordinary RAM. Shared temporary homes count once; reserved cells are excluded from the available total. Startup-only accesses do not compete as frame traffic when the compiler chooses these homes. When repeatedly used values fill the available cells, Adder can use more fast memory automatically. It saves the state needed for returning to BASIC; that small startup cost can pay for itself in the first few frames.
The Frame
A television electron beam paints the screen from top to bottom about fifty times a second on European (PAL) machines and sixty times a second on North American (NTSC) machines. Each complete sweep of the screen is one frame, and an Adder program runs its main loop in lockstep with that sweep—once per frame.
Order in a Frame
Each frame begins the instant the video beam reaches picture row 205, just below the bottom edge of the 200-line picture window. The program then runs four steps in order:
- It samples the keyboard, joysticks, paddles, mouse, and other hardware readings so they stay steady for the whole frame.
- It checks which events occurred in this frame.
- It runs the
whenhandlers for those events, in the top-to-bottom order they appear in your source. - It computes the final output values from the state left by the handlers and writes the updated outputs to the machine.
Pure bindings read inside handlers use current dependencies at that point. Bindings with memory update on their own clocks before handlers and hold those results when read.
Once step 4 finishes, the program waits for picture row 205 to come around again. A light frame waits until the next frame boundary. Your game keeps the same pace whether a frame takes 2,000 cycles or 15,000 cycles, as long as the work fits inside the frame. See Order in a Frame for how bindings and handlers interleave across these steps, and Events and Handlers for how events trigger.
Frame Lengths
A television frame lasts a fixed number of processor clock cycles, determined by the video chip inside the machine. To make sure your program runs smoothly everywhere without slowdown, the compiler checks every frame against all three video chips found in Commodore 64 hardware:
| Machine | Lines | Cycles a line | Cycles a frame |
|---|---|---|---|
| PAL | 312 | 63 | 19,656 |
| NTSC | 263 | 65 | 17,095 |
| early NTSC | 262 | 64 | 16,768 |
The early 64-cycle-per-line NTSC video chip lived in the first wave of North American machines. The processor clock frequency differs slightly between PAL and NTSC. The frame budget is counted directly in processor cycles on each chip.
The Video Chip's Share
The processor does not have the memory bus all to itself: while the video chip draws the visible window, it periodically pauses the processor for a moment to fetch graphics data. On one scanline out of every eight (the famous "badlines" at the top of each character row), the video chip borrows 40 to 43 cycles to fetch character codes or color pointers; each visible sprite also borrows 2 cycles on every scanline it spans, plus a few bus-handover cycles before the processor steps back in. Because an Adder frame starts at picture row 205 in the lower border, short frame work finishes while the beam is still in the vertical border, before the video chip borrows a single character-row cycle. Longer frame work stretches down into the visible window, where the video chip takes its share of cycles along the way.
The compiler automatically accounts for the video chip's share when computing your frame's worst case, right alongside any raster-line interrupts your program uses and the runtime's own small bookkeeping steps at the start and end of the frame.
A single unexpanded sprite at a fixed Y can keep its 21-line fetch bound beside a scrolling color grid. Its raster binding must finish before picture row -3 and before the sprite's first fetch. The compiler checks the final register writes and handler timing on all three standards; unknown values or additional timing writers keep the conservative bound.
Region scroll service
A 24-row terrain uses a service on picture row 191, its last pixel line. The linked best and worst paths place the horizontal-scroll store in the border window from picture row 191 cycle 57 through row 192 cycle 14. Cycle numbers here start at 1. A smaller top band uses the corresponding last pixel line and next badline.
The service saves the accumulator, acknowledges the interrupt during its delay, and restores a still HUD with 40 columns. The current 51-cycle prefix and 7 cycles the processor needs to start the interrupt put the earliest store at line 242 cycle 58. The latest bound also allows 9 cycles of instruction latency, including a taken branch's delayed interrupt poll:
| Standard | Earliest store | Latest store |
|---|---|---|
| PAL | Line 242, cycle 58 | Line 243, cycle 4 |
| NTSC | Line 242, cycle 58 | Line 243, cycle 2 |
| Early NTSC | Line 242, cycle 58 | Line 243, cycle 3 |
VICE checks with ordinary machine-font text at all eight pixel offsets observed line 242 cycles 60–63 or line 243 cycle 1 on PAL, and line 242 cycles 60–64 on both NTSC chips. Every terrain seam pixel and all 40 HUD columns matched the font. These observations sample real paths; the linked bounds include all admitted latency.
The same-source cost comparison charges 93 cycles per frame for the corrected service, up from 57. Its complete handler takes 60 processor cycles plus the 7 cycles the processor needs to start the interrupt; the frame report also allows interrupted-instruction and video-chip delays. Startup adds 25 bytes and 54 cycles once: 34 cycles set up and settle a CIA 2 timer A one-shot, and its first NMI takes 20. Its unacknowledged interrupt then holds NMI low, so RESTORE adds no seam delay. Sprite DMA overlapping the seam refuses.
The Scrollable world example scrolls a 160-column city and uses 10,746 file bytes and 10,981 resident bytes. Its static frame bounds are PAL 14,700 of 19,656 cycles, NTSC 14,915 of 17,095, and early NTSC 14,958 of 16,768. Its own layout charges the row service at 95 cycles per frame. Startup still has an unknown bound in the existing compressed-data unpacker.
Exact Figures and Upper Bounds
When you open the cost report, the byte column is exact: each source line compiles into that exact number of bytes in your .prg file. The cycle column is a guaranteed upper bound. The compiler sums the documented 6510 cycle count of every emitted instruction, follows the slower path through every conditional branch, and normally multiplies the longest turn of a bounded loop by its maximum trip count.
For a direct handler loop containing only if active then, a whole private byte-list copy and active = false, the compiler can prove the copy and clear run at most once during the whole loop. Its report says so and still counts every guard test, setting the counter and leaving the loop. Nested loops, calls, aliases, mapped storage, assembly and interrupts keep the conservative bound. This improves the reported bound without changing the generated instructions. At run time, a line may finish in fewer cycles than its figure, but never more.
A single-character mark right after a cycle figure tells you what kind of bound you are looking at:
| Mark | Meaning |
|---|---|
+ | The line can finish faster than this figure (for instance, when a branch skips work or an indexed load avoids crossing a 256-byte page boundary). The number shown is the worst case. |
k | The figure is rounded in thousands, such as 11k+. |
? | The compiler cannot find a finite cycle bound for an asm loop or call on this line. |
* | The figure depends on a cycles(...) or runs(...) declaration on an asm block. |
! | The line contains hand-written assembly whose memory stores the compiler takes on trust. |
See Assembly for how asm blocks declare their cycle counts.
For a plain text case, the match line also gives a conservative shared-screen showing bound in frames. It starts after the last text write or case change, with geometry fixed and no failure or direct display store. It includes progressive word-layout preparation, pending row copies, a stale hidden pass and a fresh pass, and the following border flip. A change can show sooner than this bound. Further writes or case changes can keep replacing the waiting image, so this is not a promise that a continuously changing picture will settle after that many frames. Bitmap cases, changes between screen kinds and some word-layout combinations with untracked copies do not yet have this whole-image figure; those word layouts say that no showing bound is reported. When a word layout is prepared in full before any rows are shown, the report gives a one-frame bound if all that work fits.
For blocks side by side, the bound includes shared work once plus the dearest steady or starting case of each independent block. The report names the contributing block and case. Nested alternatives remain exclusive. Complete initialization must fit its frame; the cost of composing a held image is charged beside the new case's running handlers.
A frame handler can also separate a consumed keyboard stroke from an idle cached-screen update. When one keyboard handler fills a private optional value, every frame consumes and clears it, and the compiler proves the screen queues drain on each path, it prices the complete stroke and idle paths separately. It still counts held-key scanning and every cell or row copy that can run. If another write, a wait, a shared value or an unproved path breaks those conditions, the conservative total stays. This changes the reported bound without changing the generated instructions. The cost report says whether separate key/idle accounting was applied and names the video standards where it lowered the bound.
To check a frame, the compiler totals the worst-case cycles of every line that can run in that same frame, adds the runtime's frame-loop overhead, and folds in the video chip's share. That total is a deductive proof, not a stopwatch sample from one test run: no combination of player inputs or branch choices on any of the three video standards can ever push the frame past that number. If any line that runs during the frame has an unknown (?) cycle count, the whole frame's bound is unknown too, and the cost report highlights it.
Frames That Do Not Fit
Under the default strict policy, whenever a frame's proven worst case exceeds the cycle budget of PAL, NTSC, or early NTSC, the compiler stops and shows you a breakdown of what happened. It points to the single costliest line in that frame and prints the frame's worst-case cycle total right next to the hardware's cycle budget. For a row of text or colors that must wait for the screen, the message also shows which row sets the limit and the number of cycles over budget. Why catch this at compile time? Because if a frame's work spilled past picture row 205, its screen updates would land a frame late (or mid-screen), and the game would stutter to half frame rate whenever that path ran.
Allowing Slower Updates
A calculation can be useful even when it takes several display refreshes. This program computes a CRC-16, a check number for a packet's bytes, when joystick 2's fire button is pressed. It changes the first byte before each calculation and shows the checksum's low four bits as the border color:
#allow frame_skips
var packet: [128 of Number<u8>] = 37
var checksum: Number<u16> = 0
when System.joystick[2].fire.pressed
packet[0] = packet[0] +% 1
checksum = 65535
for byte in packet
checksum = checksum.bitwise_xor(Number<u16>(byte))
for bit in 0...7
if checksum.bit_is_set(0) then
checksum = checksum.shift_right(1).bitwise_xor(0xa001)
else
checksum = checksum.shift_right(1)
end
end
end
end
System.screen.border <- Color(checksum % 16)The packet is mutable, so the compiler must account for the whole calculation over its current bytes. With #allow frame_skips, this program builds with a slower-update warning and finite cycle bounds. Remove that first line and the same program is refused because the complete loop does not fit one frame, even after the normal search for faster forms. The calculation finishes without being interrupted to make another input sample; a quick press and release during it can be missed. Release and press fire again after it finishes to check the next packet.
Place #allow frame_skips before includes and every other statement in the main source file. Comments and blank lines may precede it. The directive appears at most once; included libraries and nested bodies cannot select the program's timing policy. The choice travels with the source through the CLI, Lab and VS Code, with no build-setting override.
Adder first tries its normal one-refresh proof and faster forms. A fitting program keeps the same executable, scheduling and timing services, with no slower-update warning. Only when that fails for finite ordinary work does the compiler consider slower admission. The initial profile supports bounded private-state and list calculations, sampled digital inputs, and simple immediate outputs such as border and background colors. Rendering, starting a case, waits, elapsed clocks, seconds or milliseconds durations, interrupts, input checkpoints, keyboard repeat or line services, jobs, drives and unmodeled assembly or hardware effects still require their existing timing guarantees. Memory, arithmetic and conflicting uses of resources remain errors.
An admitted slower build succeeds with a warning. Cost details give separate PAL, NTSC and early NTSC bounds for live update work and for the gap between update starts, including repeated display contention and the actual boundary wait. These are conservative worst-case bounds, rather than a measured frame rate. Exempt boot and the first top-level when start stretch retain separate startup reporting. If the compiler cannot establish the complete finite bound, it refuses the build.
One logical update samples input, determines events, runs the reached handlers and updates the outputs once. Frame counts, frame-counted cadences and random draws follow those executed updates. Refreshes crossed by expensive work do not add extra updates or catch-up passes. An update keeps its original input snapshot; a quick press and release entirely between samples can be missed. The physical display continues refreshing, and immediate writes across several refreshes have no atomic or tear-free presentation promise. Use the existing batching and wait facilities when work needs to share time with rendering or other timing services.
A Frame Too Long
When straight-line work (rather than a single heavy loop) pushes the total past the budget, the compiler reports frameOverrun. For example, formatting three 16-bit numbers with .digits(...) on the same frame does repeated divisions that together add up past the PAL and NTSC budgets, producing this message:
Remove one of those three lines and the worst case falls to 14,393 cycles on PAL and 14,651 on early NTSC. That fits every chip's frame budget, so the program compiles.
A Loop Too Long
A for finishes inside the frame it starts in. When the costliest line is a loop, the compiler refuses with loopOverrun and gives its turns and each turn's cost. For a handler that multiplies 128 pairs of numbers, even the table routine does not fit:
The compiler has already selected the multiplication tables. The refusal names the selected line, its added bytes and saved cycles, and the remaining frame bound. With 64 pairs, the unmarked program fits by selecting those tables automatically, as fast shows. Loops and the Frame gives the rule for loops inside handlers.
A Stretch Between Waits
Inside a handler that uses wait(n), your code does not have to finish all at once in a single frame: instead, each frame runs one stretch of code—from the start of the handler (or from one wait) up to the next wait. The compiler checks each individual stretch against the frame budget, and if any stretch between two waits can take longer than a frame, it reports segmentOverrun and points to the wait where that stretch began. For instance, a for loop of 200 turns followed by wait(1) after the loop still runs all 200 turns in a single stretch before reaching the wait. Move wait(1) inside the for loop body, and each frame runs just one turn before pausing for the next frame. Because the compiler checks the longest possible path from one wait to the next, hiding a wait inside an if branch does not break up the path when the if condition is false. If a 200-turn for loop only calls wait(1) on every tenth turn via an if, the compiler sees that the if could be false on consecutive turns and reports the exact inner/outer loop pattern that guarantees a pause in time:
Splitting the 200 turns into an outer loop of 8 batches and an inner loop of 25 turns per frame makes the wait(1) unconditional on every batch:
var a: Number<u8> = 3
var b: Number<u8> = 5
var r: Number<u16> = 0
when start
for part in 0..<8
for i in 0..<25
r = r +% a * b
a = a +% 1
end
wait(1)
end
end
System.screen.border <- Color(r % 16)Work Without a Limit
Every Adder for loop has a known range, so pure Adder code always has a provable cycle bound. An asm block, however, can branch backward on a hardware register or a memory byte whose trip count the compiler cannot deduce, jump or jsr to an external address, or call a subroutine recursively. When an asm block runs during a frame and the compiler cannot prove where its loop or call ends, it flags frameUnbounded and points to the instruction or label responsible. For example, if an asm block inside a frame handler spins in a loop waiting for a raster line, the compiler tells you how to supply the cycle bound:
Adding the cycles(...) clause on the asm line gives the compiler your worst-case figure on trust when it cannot count the block. When it can count the block, it uses its own figure and adds a note saying you can remove the clause. When it can only show that the declared maximum is too low, it charges at least the proved minimum and asks you to raise the maximum. If the corrected figure no longer fits the frame, you get the usual frame-budget error. The cycles Clause There is one natural exception: work that runs once at boot before the very first frame has no 50/60 Hz deadline to race against. That includes the runtime's own start-up setup and the initial stretch of a top-level when start handler (before its first wait). If you put an uncounted assembly loop in that initial top-level start-up stretch, the program compiles without complaint, the cost report notes the ? on the start-up row, and normal frames are still verified as usual. By contrast, a when start handler inside a case—or any code in a top-level when start after its first wait—runs while live frames are ticking, so an uncounted loop there needs cycles(...) just like any other handler. And if an asm block tries to wire up hardware interrupt vectors by hand instead of using an Adder interrupt handler, the compiler flags interruptInstall regardless of where the block sits, as described in Interrupt Routines.
Every frame the compiler builds comes with a count of the cycles its work takes, on every video standard. If the compiler ever meets work in a frame that it cannot count, and the work is not in an asm block of yours, it refuses the program with frameUnproved instead of building it unchecked. That refusal is a gap in the compiler, not a mistake in your program; its message says so and asks you to report the program. The one exception is a disk drive. A transfer takes as long as the drive does, so a program that loads or saves a file keeps an unknown figure for its frame, and the cost report says so on the line of each drive call. A list of text or colors the screen would show in place is copied to the screen instead, because a write to it while it is on show has to wait for the screen's drawing, and the drive leaves the frame's time unknown; the cost report says so on the binding's line. Any other write the compiler has to place against the screen's drawing still can't be shown to land in time beside a drive, and the program is refused with frameUnproved.
When the Compiler Spends Bytes Itself
The default uses compact code. When a frame does not fit, the compiler selects faster forms from the list below, taking the most cycles saved for each added byte and using source order to break ties. It stops when PAL, NTSC and early NTSC all fit, while the program still fits in memory. The cost report names each selected change on its line. A frame that still does not fit names the changes taken and the work left.
For a top-level match between fixed hires drawings and colors, the compiler prepares the next bitmap in separate storage while the previous whole image stays visible. It needs another 8,000 bytes for pixels, 1,024 for cell colors and sprite pointers, and 64 for each sprite shape. These parts must fit at the display's allowed positions beside the program and its other data. When they do not fit, bitmapSecondImage reports the bytes needed and the available space; a large but fragmented free area may still be unsuitable.
Automatic Savings
The compiler can make ordinary code smaller and quicker without a fast mark. Repeated frame events with the same interval can share a counter, and small private calculations can avoid unnecessary change checks. Record and list results can fill a new local directly instead of taking another copy. Numeric helpers can use proven byte values or constants from their callers, and values can stay in processor registers across branches.
These choices keep the program's checks, captured values and event schedules. The compiler compares complete program costs before choosing specialized helper code, keeping shared code when expansion would cost more. Use the cost report to see the result for your program; the savings depend on the values, calls and work it contains.
fast
Putting the keyword fast in front of a declaration tells the compiler: "In this declaration, feel free to spend extra program bytes to generate faster machine code." You can place fast before these code-owning heads:
| Head | Example |
|---|---|
a when handler | fast when System.screen.frame |
| a function | fast fn square(x: Number<u8>): Number<u16> |
| a function inside a struct | fast mut fn award() |
| a service action | fast action show(value: Number<u8>) |
| an op | fast op speed(x) |
| a binding or an output | fast moved <- position * 2 |
| a case | fast game -> |
a declaration if | fast if playing then |
| a region declaration | fast const log = System.screen.region(row: 1) |
You can find the full syntax of each declaration head in Declarations and Events and Handlers. A fast mark applies to all the code inside that declaration, including helper functions copied into it. Other code stays compact when its frame fits.
The 64-pair program fits on every chip. Without a mark, the frame selects its tables; with fast, the handler asks for them whether or not its frame needs them:
var weights: [64 of Number<u8>] = 3
var levels: [64 of Number<u8>] = 5
var mix: Number<u16> = 0
fast when System.screen.frame
var acc: Number<u16> = 0
for i in 0..<64
acc = acc +% weights[i] * levels[i]
end
mix = acc
end
System.screen.border <- Color(mix % 16)The multiplication row says whether the frame or a written mark selected the faster routine. Its two tables and shared routine are counted once on their own report row.
What fast Spends
fast only alters operations that have a faster, larger machine-code strategy available:
| In fast code | Without fast | With fast |
|---|---|---|
* of two changing values | a compact 24-byte shift-and-add routine taking up to 181 cycles | a quarter-square lookup routine backed by 512-byte tables, taking 74 to 81 cycles |
| a case's list that starts as one repeated value | filled by a compact loop when the case starts | filled by an unrolled run of stores (3 bytes and 4 cycles per byte of the list) |
| a loop that copies a run of bytes | a compact indexed loop | unrolled to eight bytes per turn, or one straight copy per turn |
| a call of a function body in assembly | jsr to one shared subroutine body | inlines a copy of the assembly body right at the call site |
a list of sprites made with map | updated through one shared loop body | unrolled into direct stores to each sprite's hardware registers |
| a region's rows | built by one shared routine | each row built by dedicated code of its own |
No matter how many fast declarations use fast multiplication, your program carries at most one shared copy of the quarter-square lookup tables (1,083 bytes including the routine), listed on its own row in the cost report. The tables leave the program when no line needs or asks for them. Removing a fast mark still lets the frame select faster code when it needs it. Even better, once the lookup tables are already in your program because of one fast block, the cost report annotates any remaining slow multiplications elsewhere in the program to show how many cycles fast would save there for zero extra table bytes! Marking an assembly function fast fn inlines its asm body at every call site instead of calling it with jsr.
If you put fast on a declaration where none of the strategies in the table apply, your program still compiles cleanly, and the cost report simply notes fast changed nothing here on that line.
Keeping Code Compact with small
small belongs on the same code heads as fast: a function, op, handler, binding, case pattern or region declaration. It keeps the compact forms in the table above even when a frame needs faster code. An unmarked copied body inherits the caller's choice; a marked body makes its own choice. A small handler inside a fast case stays compact, and a fast handler inside a small case uses the faster forms.
The cost row says small: kept compact, with the complete image bytes and frame-bound cycles its faster alternative would add or save. If there is no alternative on the list, it says small changed nothing here. Regions that share one composed row have one shape decision, so their alternatives are labelled with all source lines and a joint byte difference. Explicitly conflicting fast and small marks on that shared code are refused.
The compiler first takes any allowed faster forms elsewhere. If removing small marks would then let every frame fit, the refusal names the necessary lines, the extra bytes and the remaining work. The reported alternative leaves the program compact, and the same byte and frame limits apply.
Where fast Cannot Go
Because fast speeds up executable code, it only belongs on heads that own code. A region declaration can carry it; an ordinary fixed value, a var, or a type declaration cannot (fastHead).
The same rules apply to small. Repeating one mark on a head gives fastRepeated; writing fast small or small fast gives codeMarkConflict. Neither mark rewrites an asm block (fastAsm). A mark on a case may contain marked handlers or nested cases: the innermost mark decides their code. An explicitly marked function or op keeps its choice when its body is copied into differently marked code.
Work Divided Between Frames
The strict single-frame check applies to code that runs from start to finish inside one frame. For heavier tasks that naturally span several frames, Adder provides five built-in ways to spread work across time—and the compiler checks each per-frame step on its own:
- A handler that calls
wait(n)runs one stretch per frame between waits, as shown in A Stretch Between Waits. - A
workmember runs as a background job in whatever cycles remain at the end of each frame after the frame's main handlers and bindings finish. - A complex canvas drawing change is rendered incrementally across frames so the frame loop stays on time.
- Text printed to a region is copied out to screen memory a few rows per frame.
- A case's visible picture can be prepared across several frames while the previous complete picture stays visible. Its state still initializes completely in its starting frame, before its handlers run.
Let's look at how background work jobs are divided into parts and verified. See Work for how to declare a work member, and The System Device Tree for canvas drawings and text regions.
Parts of a Job
When you write a work job, the compiler automatically breaks its body into bite-sized parts along the turns of its loops. A short loop that easily fits in a frame becomes a single part; a longer loop is grouped into a handful of turns per part; and straight-line code without loops is one part. Before starting each part at run time, the job scheduler checks how many cycles are left before the next television frame begins, and runs the next part only if it is guaranteed to finish before picture row 205. If there is not enough room left in the current frame, the job yields right there and picks up at that part on the next frame.
Because a background job yields whenever a frame is nearly full, a bound job can run alongside any frame that leaves enough breathing room for the job's longest single part:
type Samples = [4 of Number<u8>]
work tally(input: Samples): Number<u16>
var amount: Number<u16> = 0
for sample in input
amount = amount + sample
end
amount
end
const samples: Samples = [1, 2, 3, 4]
answer: Number<u16>? <- tally(samples)
System.screen.text[0][0..<5] <- if amount = answer then amount.digits(5) else "wait " endThe compiler verifies every job at build time so a background task can never stall or overrun a frame:
- if a part of a job contains an uncounted loop with no cycle limit, it flags
jobUnbounded; - if a single part—one turn of a loop, or the straight-line code before or after a loop—is too large to ever fit alongside the frame's regular work, it flags
jobPartTooLongand names the loop; - if a handler explicitly calls
.resume()on a job in a frame that has no cycles left to spare for a part, it flagsjobFrameFull; - if a binding asks for a guaranteed completion window with
.within(frames: n)and the compiler cannot prove the job finishes withinnframes under worst-case frame load, it flagsjobDeadlineand tells you the shortest deadline it can prove.
Because the static deadline proof reserves cycles in every frame for the scheduler's remaining-time check before each part, the proven worst-case deadline is safely conservative—at run time the job will often finish even sooner.
The Cost Report
Want to see the exact byte and cycle ledger for your whole program? Run adder costs on your source file or project folder:
adder costs game.adder
adder costs game.adder --listingPass --listing to unfold the exact 6510 assembly instructions emitted under each source line along with every instruction's individual cycle count. If your program has a compile error or a frame overrun, adder costs prints the diagnostic message instead and leaves with status 1.
Explain the Frame Bound
Run adder costs game.adder --explain-frame to see the work that sets the bound on PAL, NTSC, and early NTSC. The report shows the chosen source arms where the compiler can break down the proof. It counts shared continuations once, marks a named assembly allowance as declared, and separates interrupt, video, and frame-boundary costs. A combined cost for a case or a drawing routine can appear as one proved row.
The figures are upper bounds. For example, the compiler can count the longest joystick read together with the longer arm of an if. The explanation reports those choices even if they need different joystick states.
The compiler package exposes the same tree in frameExplanation when you pass { explainFrame: true } as the fifth argument to compile. Source locations in the tree point to the original files, including included files.
Reading Costs in the Lab
Hover or focus a cycle figure beside your source to see a short cost card. It shows the static cycle bound, its share of a PAL frame, Program bytes here, and Working storage here. Activate the figure to open the 6502 inspector. The cost explanation stays available in both Woven and Flow, beside the generated instructions.
"Here" means attributed to this source line. Program bytes include instructions and any inline data; working storage includes variables and scratch space. A small call can use a larger shared routine whose bytes are attributed elsewhere. Existing shared and deferred-work notes explain that work where the compiler reports it. Per-line upper bounds cannot simply be added to recover the complete frame total, because branches can be exclusive and loop headers already include their turns.
May change groups a call's effects by the places you wrote, such as System.screen or a mutable list. Open the exact writes and expanded-call details to inspect individual fields and ranges. Compiler helper names belong in those details, so the short card stays readable. Source hovers and command-line cost reports use the same authored effects.
The card retains unknown, lower-bound, declared and trusted qualifications. Its cycle figure describes processor work within the reported scope, not an emulator measurement or elapsed display time. Loop-body rows describe one turn when marked that way. The complete frame report also accounts for interrupt and video-chip interference. Edited source keeps a stale indication until recompilation succeeds; Escape dismisses a transient card.
Reading the Report
Here is the cost report for the fast 64-multiply program from fast:
source bytes cycles
mix.adder:4 4 5+ fast when System.screen.frame
fast: tables in 1 multiplication
mix.adder:6 10 11k+ for i in 0..<64
a loop of 64 turns of at most 178 cycles: 64 × 178 = 11,392; the figure also holds the cycles that set the counter and leave
mix.adder:7 57 165+ acc = acc +% weights[i] * levels[i]
fast: tables, 165+ cycles instead of 263+, no extra bytes
one turn of the loop at mix.adder:6, whose figure holds every turn
fast multiply tables, 1,083 bytes, used by line mix.adder:7
frame work, worst case: PAL 11,962 of 19,656 cycles, NTSC 12,220 of 17,095, early NTSC 12,263 of 16,768
runtime and shared tables (line 0): 1393 bytes (258 code, 1135 data and padding); startup worst case 13,806 cycles; program file: 1537 bytes including the load addressEach numbered row shows the file and line number, the exact bytes emitted for that line, the worst-case cycle bound (with its mark), and the source text itself. Indented notes right underneath a row explain how the compiler arrived at the number: how many turns a loop runs, what fast changed, and any shared tables or storage claimed by that line. Notice that the for loop header row (mix.adder:6) holds the total cycle count of all 64 turns combined (11,392 plus loop setup), while the body line inside it (mix.adder:7) shows the cost of a single turn (165+) so you can see both without double-counting.
Near the bottom, the frame work, worst case summary compares your program's proven worst-case frame against the cycle budget of PAL, NTSC, and early NTSC side by side. Finally, the runtime and shared tables (line 0) row accounts for the shared machinery bundled into the .prg—start-up initialization, hardware input sampling, the frame loop, the range-overflow stop handler, and any shared lookup tables like the fast multiply tables—along with the final .prg file size on disk.
The cost report makes it fun and easy to compare language choices at a glance. For example, a checked subtraction - tests whether the result dipped below the variable's minimum range and calls the range-stop handler if so, whereas a saturating subtraction -| clamps at the floor in just a few instructions:
lives.adder:3 36 28+ lives = lives - 1
runtime and shared tables (line 0): 430 byteslives2.adder:3 14 17+ lives = lives -| 1
runtime and shared tables (line 0): 307 bytesSwitching line 3 from lives - 1 to lives -| 1 saved 22 bytes and 11 cycles on that line. It also removed 123 runtime bytes. No line could trigger a range-overflow stop, so the compiler left out the stop handler.
See Checked Arithmetic and Wrapping and Clamping for the full set of arithmetic operators.
Interrupt routine figures include the whole invocation, including local initialization, generated calculations, calls, register and scratch preservation, and compiler setup and return work. The compiler counts assembly where it can and uses the trust rules above for other cycles(...) clauses. A self-arming runs(n) declaration charges that complete invocation for every run. Source rows report generated storage. Routine rows and the complete frame check include timer interference and mapped register effects, including mirrors. Interrupt Routines
Collection Pipelines and Service Actions
Pipes use the same checked calls as direct application. Collection stages keep fixed slots, invoke callbacks only where required, and complete their checks before the next stage. A total chain may share intermediate work when the compiler can prove that evaluation order and snapshots stay equivalent. Fallible callbacks and do keep their stage boundaries. Action service work is charged to the handler's frame along with the surrounding calculations; do adds one whole-value observation, regardless of how many list slots are present. Use the cost report for the complete program when comparing a pipeline with an imperative loop.
Assembly
Use an asm block to write 6510 machine instructions inside an Adder program. You can count individual processor cycles, write hardware registers on a raster line, or handcraft a bitwise routine. The compiler assembles your instructions byte for byte as written, without rewrites or optimizations. The compiler still resolves Adder variable and device names, checks for writes to reserved runtime memory, counts instructions toward the frame budget, and adds an epilogue so Adder code can continue after the block. The final section shows how the same assembler builds standalone .s files with no Adder code.
Assembly Blocks
You can place an asm block anywhere a statement goes inside a when handler—at the top level of the handler or nested inside if, match, and for statements—or as a step inside an output declaration. The block executes right where it sits each time control reaches that line. Handlers inside a case can hold asm blocks too, and all the same rules apply.
For a quick one-liner, write asm followed by a single instruction on the same line. For a multi-line routine, open with asm, write as many assembly lines as you like, and close with end. On the opening line of a multi-line block, you can optionally include a writes clause, a runs clause, and a cycles clause, in that order (where runs is specifically for self-scheduling interrupt routines).
var ticks: Number<u8> = 0
when System.screen.frame
asm inc ticks
if ticks > 200 then
asm
lda #0
sta ticks
end
end
end
System.screen.border <- Color(ticks % 16)Because an asm statement needs a handler or output routine to run in, placing a loose asm block at the top level of a file outside any handler is caught with topLevelAssembly.
And since the assembler always emits the exact instructions you write without rewriting them, putting fast in front of an asm block is flagged with fastAsm. Beyond statement blocks inside handlers, an asm block can also form the body of a function (Assembly Functions) or compute the value of a binding or assignment (Hand-Written Bindings).
Registers and Flags
Inside an asm block, the 6510's registers (A, X, and Y) and status flags (N, V, Z, and C) are yours to use freely. The compiler never assumes a value stays in A, X, or Y across an asm block—any Adder code after the block reloads whatever registers it needs. You are responsible for leaving the hardware stack pointer where you found it (every pha matched by a pla).
Right after every asm block, the compiler emits a cld (Clear Decimal Mode) instruction so that if your block switched on BCD arithmetic with sed, normal binary arithmetic is restored at end. That cld adds 1 byte and 2 cycles, which you will see noted on the end line of the cost report.
Once the runtime finishes booting and sets up the frame loop's interrupts, it clears the processor's interrupt-disable (I) flag and keeps it clear. An asm block may temporarily mask interrupts with sei, but only a top-level when start block is allowed to execute cli; writing cli anywhere else is flagged with assemblyCli so a block cannot accidentally enable interrupts at the wrong moment.
The writes Clause
Whenever your assembly block stores directly to an Adder variable or binding by name—like sta ticks or inc ticks—the compiler spots the store automatically. Right after the block's end, it sets that variable's change flag so any downstream bindings that depend on ticks know to recompute on this frame. Those automatic change marks cost a 2-byte, 2-cycle lda #1 followed by a 3-byte, 4-cycle store per modified variable, shown on the end line in the cost report.
What if your block modifies an Adder variable indirectly through a zero-page pointer in scratch, where the instruction says sta (scratch),y instead of naming ticks? Add writes(name, ...) on the opening asm line to tell the compiler which variables or bindings your pointer store touches:
var ticks: Number<u8> = 0
seen <- ticks
when System.screen.frame
asm writes(ticks)
lda #<ticks
sta scratch
lda #>ticks
sta scratch+1
ldy #0
lda (scratch),y
clc
adc #1
sta (scratch),y
end
end
System.screen.border <- Color(seen % 16)Every name listed in writes(...) must be a variable or binding declared above the block (assemblyWritesName). If you leave a pointer-modified variable out of writes(...), downstream bindings will not know it changed and will keep displaying their previous value.
The cycles Clause
Normally, the compiler traces every path through your asm block and sums the exact 6510 cycle counts itself. It also counts ordinary jsr calls to shared helpers in an earlier top-level when start when every reached helper has a finite cost and a balanced return stack. Straight-line helpers and loops with fixed counts need no cycle declaration; nested and repeated calls each include their complete work. However, if your block contains a loop whose trip count depends on a runtime register or hardware state, a jsr or jmp to an external address, or a recursive call, the compiler cannot deduce the maximum cycle count on its own (frameUnbounded, as described in Work Without a Limit). In those cases, add cycles(...) on the opening asm line and state the most time the block can take. When the compiler can count the whole block, it uses its own count and adds a note saying you can remove the clause. For instance, a block containing only nop costs two cycles even if you wrote cycles(1). When the compiler only knows a minimum and your figure is below it, the frame pays at least that minimum. The note asks you to raise the declared maximum to include the whole block. You still need to account for any time the compiler cannot count.
Write cycles(n) for a single cycle figure or cycles(low...high) for a minimum-to-maximum range that applies across all video standards. If your block's timing differs between PAL and NTSC (for instance, when waiting for a specific raster scanline), you can give separate figures per video standard using pal:, ntsc:, and optionally early_ntsc:. When you write ntsc:, that figure applies to both standard NTSC and early NTSC unless you also write an explicit early_ntsc: figure.
var delay: Number<1...200> = 1
when System.screen.frame
asm cycles(8...1203)
ldx delay
wait:
dex
bne wait
end
endFor example, a raster wait loop whose duration depends on the television standard can declare cycles(pal: 4800...16700, ntsc: 4800...14100).
To keep per-standard declarations complete, specifying pal: without ntsc: (or ntsc: without pal:) is caught with cyclesOneStandard. The compiler also checks for unknown standard names (cyclesStandard), duplicate standard names (cyclesRepeated), non-integer cycle counts (cyclesNeeded), and zero or inverted ranges where the minimum exceeds the maximum (cyclesRange).
In the cost report, * marks a figure that depends on your declaration. Run adder costs game.adder --explain-frame to see the declared figure and the bounds the compiler can prove. A CPU minimum leaves out device wait time. The ! mark reminds you that an ordinary assembly block's memory stores are taken on trust. See Costs and the Frame for how both marks appear in the report.
Assembly With a Completion Deadline
A completion deadline can include foreground assembly whose complete instructions, memory accesses and return paths the compiler can check. Use named RAM values, including typed names mapped to RAM, so each access has known storage. The check examines the whole program, including assembly outside the marked handler:
var ticks: Number<u8> = 0
sample: Number<u8> at 0xC000
when System.screen.frame.deadline(line: -1)
asm
lda sample
sta ticks
end
endChanging lda sample to lda $C000 in this example is refused: a numeric operand does not identify the named RAM value, even at the same address. Keep the declaration and use lda sample. An unresolved pointer access is also outside this checked boundary.
Local subroutines and shared routines defined in an earlier when start can be included when every reached callee is known, bounded and returns with a balanced stack. A loop must have a proved finite count, and indexed accesses must stay within the named storage. The compiler checks the actual instructions and the typed values reaching each access to establish those bounds. Assembly functions called by foreground work keep their ordinary purity and result checks as well as these memory and timing requirements.
A call into a shared when start helper needs no cycles(...) when the compiler can count its ordinary cost. If it cannot, put the allowance on the calling block. The completion proof still checks the actual callee separately; an allowance cannot establish a completion proof.
The ordinary cycle allowance and the * and ! cost-report marks stay the same. writes(...) still tells Adder which values may change. A completion deadline additionally counts the linked instructions and their callees: an understated cycle allowance cannot make unproved work meet the deadline. If a call, loop or return cannot be checked, supply a known, bounded callee or simplify the routine until every path can be checked.
Interrupt routines keep their own clock, storage and return rules. Assembly implementations of clock-qualified bindings remain refused, and captured values retain their write protection and their limits on when they can be read. Hand-written bindings and output implementations, callbacks, action calls, imported byte functions and cooperative work remain outside this additional assembly boundary.
Elapsed-time clocks can share a program with verified assembly. The compiler also checks every possible access, including incidental reads, against the clock's CIA 2 timer A, its control and interrupt-status registers and their mirrors. The clock's own counter storage stays protected. Keep those resources under the clock's control when writing an otherwise bounded RAM routine.
Lines of a Block
Each line inside an asm block can hold a label, an instruction (with or without a leading label), or a data directive (.byte or .text). Comments start with // just like in the rest of Adder, and indentation is purely visual.
Instructions
An asm block supports all 56 official mnemonics of the MOS 6510 processor in either lowercase (lda) or uppercase (LDA). You can find the complete alphabetical list in Words Inside Assembly.
Adder supports the stable undocumented ("illegal") NMOS 6510 opcodes, which behave identically across every production 6510 chip:
| Instruction | What it does |
|---|---|
lax | loads both A and X with the same memory byte |
sax | stores A bitwise-ANDed with X into memory (without changing flags) |
dcp, isc, slo, rla, sre, rra | read-modify-write a memory byte, then combine it with A |
anc, alr, arr, sbx | immediate operations on A (or A and X) with a constant byte |
nop with an operand | fetches its operand (consuming the addressing mode's bytes and cycles) and does nothing else |
If you are used to alternative assembler spellings, isb, asr, and axs are accepted as synonyms for isc, alr, and sbx.
What about the unstable undocumented opcodes whose behavior varies with chip batch, temperature, or bus capacitance (ane, lxa, sha, shx, shy, tas, las, and immediate lax #n which is lxa)? The compiler keeps them out of your program with assemblyUnstable so your code runs identically on every machine, and it blocks jam (kil/hlt) with assemblyJam since a JAM opcode freezes the 6510 until you power-cycle the computer.
Every instruction accepts only the addressing modes that actually exist for it on the 6510; writing a nonexistent mode (like sta #0 or inx #1) is caught with badInstructionForm or assemblyForm. In a single-line asm statement, an unrecognized mnemonic is flagged with unknownInstruction.
Operands
Operands use classic MOS 6502/6510 addressing syntax:
| Form | Meaning |
|---|---|
#value | immediate: the 8-bit constant value itself |
address | zero-page or absolute: the byte stored at address (or label target for branches/jumps) |
address,x or address,y | indexed: the byte at address + X or address + Y |
(address,x) | indexed indirect: the byte at the 16-bit pointer stored in zero page at address + X |
(address),y | indirect indexed: the byte at the 16-bit zero-page pointer at address, offset by + Y |
(address) | indirect: jumps through the 16-bit pointer stored at address (jmp only) |
Instructions with implied or accumulator addressing—such as inx, clc, rts, or asl shifting A—take no operand at all.
Inside an asm block, numbers use traditional 6502 notation: decimal (14), $ for hexadecimal ($0e), or % for binary (%00001110). Notice that Adder's 0x and 0b prefixes belong to high-level Adder expressions; inside an asm block, use $ and % instead (badNumber). A leading minus sign - gives the 8-bit two's-complement byte, so lda #-1 loads $ff. Every immediate #value must fit in a single byte (-128 to 255), or the compiler flags operandSize.
Prefixing any value or symbol with < extracts its low byte (bits 0–7), and > extracts its high byte (bits 8–15). When placed in front of a variable, label, or device name that lives in memory, <name and >name give you the low and high bytes of its 16-bit address—so lda #<ticks loads the low byte of the address of ticks.
Whenever a numeric address falls in $00–$ff and the instruction supports zero-page addressing, the assembler automatically picks the compact 2-byte zero-page opcode (whether you write $fb or $00fb). Named Adder variables and bindings always assemble with 16-bit absolute addressing.
Labels
Writing name: defines a label at the address of the next instruction or data byte. A label can sit on its own line or right in front of an instruction or .byte/.text directive on the same line, giving branch and jump instructions a clear target:
var pos: Number<u16> = 0
when System.screen.frame
asm
inc pos.lo
bne done
inc pos.hi
done:
end
end
System.screen.border <- Color(pos % 16)Labels are local to their own asm block, so two separate blocks can both have a label named done without clashing. There is one handy exception: labels defined inside a when start handler remain visible to every asm block written below that when start in the same scope, making it easy to share lookup tables or helper routines (see Start-Up Code). A case's when start shares its labels only with blocks inside that same case (and any sub-cases nested inside it), so two sibling cases can reuse the same label names cleanly.
To prevent ambiguity, a label cannot shadow an Adder name or another label already in scope (assemblyLabelCollides), nor can it reuse a built-in name like Color or scratch (builtinName). Because a label is an address rather than a multi-byte variable, use <label and >label to take the low and high bytes of its address rather than .lo or .hi (assemblyLabelSelector). Finally, 6510 conditional branches (beq, bne, bcc, and friends) use a signed 8-bit relative offset that reaches at most 128 bytes backward or 127 bytes forward from the following instruction; if a branch target is farther away than that, the assembler lets you know with branchTooFar.
Data
You can embed data tables right inside an asm block using .byte for comma-separated bytes and .text for a string literal converted into screen codes (matching ScreenCode("...")). Each item in a .byte list can be a number (0 to 255 or -128 to -1), a named Adder constant, or the < or > byte of an address.
when System.screen.frame
asm
ldx #4
show:
lda word,x
sta System.screen.text,x
dex
bpl show
word: .text "hello"
end
endThe compiler places labeled .byte or .text data from an asm block at the end of the program's code, outside the instruction stream. You do not need a jmp to skip the data table. If any asm block writes to a labeled data cell at run time, Adder treats it like an initialized variable. It resets the cell to its original .byte/.text values whenever that scope starts: at boot for top-level blocks, or each time a case begins for case blocks. If no block ever writes to the labeled data, it stays read-only in place and costs zero start-up cycles. Writing .text without a string literal after it is caught with textNeeded.
Names in Assembly
An asm block can refer directly to the variables, bindings, constants, placed values, function parameters, and System devices declared on lines above it. Just like the rest of Adder, visibility flows from top to bottom: referencing a name declared below the block (or not declared at all) is flagged with assemblyUnknownName.
Values With an Address
Variables, bindings, placed values, and hardware device registers all live at memory addresses, so writing their name in an operand refers to the byte stored at that address. For a 1-byte (u8, i8, bool, Color, etc.) value, write its name by itself: lda ticks. For a 2-byte (u16, i16, u8.8, i8.8) value, tack on .lo for the low byte or .hi for the high byte (lda score.lo, lda score.hi); writing a 2-byte name without .lo or .hi is caught with assemblyWide, and putting .hi on a 1-byte value is caught with assemblyNarrow.
Three-byte fixed-point numbers (u16.8 and i16.8) are wider than asm operands address directly (assemblyTooWide)—if you need part of one in assembly, bind its integer part (via .floor()) or scaled value into a u8 or u16 variable first. Similarly, composite values like structs hold multiple fields rather than a single number (assemblyNeedsScalar).
Lists are laid out in assembly-friendly form:
- A list of 1-byte elements sits in contiguous bytes:
nameis element0,name+nis elementn(only 1-byte lists take+n, checked byassemblyByteOffset), andlda name,xindexes elementXat run time. - A list of 2-byte elements is stored in striped (structure-of-arrays) layout—all the low bytes together in one contiguous table and all the high bytes together in another—so
lda pos.lo,xandlda pos.hi,xcan index up to 256 16-bit elements with an 8-bitXorYregister without doubling the index!
var pos: [3 of Number<u16>] = [0x0101, 0x0202, 0x0303]
when System.screen.frame
asm
ldx #2
more:
inc pos.lo,x
bne step
inc pos.hi,x
step:
dex
bpl more
end
endConstants
A numeric constant stands for its number rather than a memory cell, so load it with immediate # syntax: lda #speed (and use #speed.lo / #speed.hi for a 2-byte constant). A list constant, on the other hand, lives as a lookup table in memory, so lda row,x reads element X from the table; because it is a constant, attempting to write to it (sta row,x) is caught with assemblyConstantWrite.
const speed = 3
const row = [6, 14, 3, 1]
var got: [4 of Number<u8>] = [0, 0, 0, 0]
when System.screen.frame
asm
ldx #speed
copy:
lda row,x
sta got,x
dex
bpl copy
end
endA struct constant groups multiple fields without a single scalar address (assemblyNoAddress).
Devices
You can read or write hardware device registers using their readable System paths right in assembly—such as sta System.screen.border or lda System.joystick[2].dx. System.screen.text always points to the first cell of screen memory (wherever the compiler placed the screen), and System.screen.text+2 points to the third cell. If your program gave a device a short alias with a constant (like screen = System.screen), use that alias (screen.border) inside your asm blocks too—the compiler flags the long path with deviceNamed so every reference stays consistent.
Sampled input devices (such as System.joystick[2].dx) hold the clean reading latched at the start of the frame; your block can read them with lda, and the compiler blocks stores to them with assemblyInputWrite.
Scratch
Every asm block has free use of four zero-page scratch bytes at $FB–$FE, named scratch, scratch+1, scratch+2, and scratch+3. Because they sit in zero page, scratch and scratch+1 (or scratch+2 and scratch+3) make a natural 16-bit pointer pair for indirect indexed addressing like lda (scratch),y or sta (scratch),y. Blocks inside when handlers can both read and write through a scratch pointer; pure assembly functions, hand-written bindings, and interrupt routines can read through a pointer (and must keep their stores to known places).
Keep in mind that scratch is a shared workbench: the runtime and other asm blocks use $FB–$FE too, so values left in scratch do not survive from one asm block to another or across frames. When you need a byte to persist, store it in an Adder var or a labeled .byte cell instead. Using an offset past scratch+3 or writing .lo/.hi on scratch is caught with assemblyScratch.
Assembly Functions
Want to wrap a fast 6510 routine in a clean, reusable Adder function call? When a function's entire body is a single asm block, it becomes an assembly function: it reads its parameters by name. A function that returns a value stores it into the built-in variable result.
fn double(n: Number<u8>): Number<u16>
asm
lda n
asl
sta result.lo
lda #0
rol
sta result.hi
end
end
var level: Number<u8> = 200
when System.screen.frame
level = level +% 1
end
System.screen.text[0][0..<3] <- double(level).digits(3)result automatically matches the return type declared on your fn header—so a 1-byte return uses sta result, while a 2-byte return uses sta result.lo and sta result.hi. The compiler traces every branch through your function to make sure every possible path writes every byte of result before returning (assemblyResultUnwritten); direct stores inside a local subroutine called with jsr count, while indirect pointer stores do not. If your function declares a constrained return range like Number<0...127>, callers rely on that promise, so make sure your assembly produces a value within that range.
Ordinary function parameters are read-only inputs (since the compiler may pass a caller's variable storage directly without copying). Attempting to modify a parameter (sta n, inc n, asl n) is caught with assemblyParameterWrite—just load it into A or copy it into scratch if you need a working variable. Also avoid naming a parameter a, x, or y, since those letters belong to the 6510 registers (assemblyRegisterParameter).
A read-only assembly function computes its result without hidden side effects on the rest of the machine. Inside a read-only assembly function, your block may write only to result, scratch, and its own labeled .byte cells (indexed or direct, such as sta table,y). Touching a System device, jumping or calling outside the function block, executing cli, rti, or brk, adding a writes(...) clause, or storing indirectly through a pointer (sta (scratch),y or sta (scratch,x)) is flagged with assemblyImpure (while reading through a pointer, such as lda (scratch),y to walk a list parameter, is completely fine). If you want a routine that mutates global program state through a pointer, place the asm block inside a when handler and list the targets in writes. Inside an assembly function, you can use rts to return early from a branch if you like (once result has been written).
Normally, all calls to an assembly function share one subroutine body in memory; putting fast fn on the declaration inlines a copy of the asm block at every call site to save the jsr/rts cycles.
Changing fields and parameters
Use a changing member to write its own fields by name. Use mut on an explicit parameter and at the call to let a free function write that place. If there is no result type, the body needs no result store.
struct Counter
var total: Number<u8> = 0
mut fn bump()
asm
inc total
end
end
end
var counter = Counter()
when System.screen.frame
counter.bump()
endFor example, fn put(mut cells: [16 of Number<u8>], slot: Number<0...15>, value: Number<u8>) can use ldx slot, lda value and sta cells,x. Call it as put(mut cells, slot, value). Adder checks that the index stays within the list and that two changing arguments cannot name the same place.
Changing assembly may read and write byte and word Numbers and their lists. Use the full numeric range of the representation for places you write, such as Number<u8>. If a place has a narrower range such as Number<0...7>, return the new value and make a checked assignment in Adder. A narrower read-only input can help the compiler prove a list index.
Adder can count an assembly loop that steps X or Y toward a fixed value. For example, ldx #17 or ldx count with count: Number<1...40> can start a loop that ends with dex and bne. The cost report gives a CPU cycle bound for each call. If Adder cannot count the loop, give the body a cycles(...) allowance as you would in a handler. The report marks the declared time with *. Every indexed access still needs a proved range.
Changing assembly has private zeroed scratch bytes and can read local labeled data. Registers and arithmetic flags start as if the function had loaded zero, with carry and overflow clear. Arithmetic is binary. Device registers, outer variables, indirect accesses and writes(...) stay outside these functions.
Hand-Written Bindings
A hand-written binding or update can stand in a case, with the same range, overlapping-output and instruction checks. It runs only while the case matches; its memory starts again with the case. An output declared above the block may also contain assembly and be bound in a case.
Sometimes you want the declarative convenience of an Adder <- binding, a variable assignment x = ..., or a placed value, while hand-crafting the exact 6510 instructions that compute the expression. Writing an asm block right after the expression gives you the best of both: the high-level expression tells the compiler what inputs the line depends on, when it needs to run, and what range the result has, while your asm block replaces the generated code and stores the answer into result.
var ticks: Number<u8> = 0
when System.screen.frame
ticks = ticks +% 3 asm
lda ticks
clc
adc #3
sta result
end
end
System.screen.border <- Color(ticks % 16)Just like an assembly function, a hand-written binding must write every byte of result on every path through the block. To make sure the dependency graph stays accurate, the asm block may only read variables and bindings that actually appear in the high-level expression in front of asm—reading an unmentioned variable is caught with handWrittenRead.
Likewise, the block is pure calculation: it may write only to result, scratch, and its own labeled .byte cells, and any store to a device, an outer variable, or an indirect pointer is flagged with handImpure. Stream-state expressions that maintain their own internal frame-to-frame memory (such as .sum(...) or .toggle()) cannot be replaced by hand-written assembly (handWrittenMemory), nor can raster-timed color-band bindings that have no single static result cell in memory (handWrittenTarget).
Start-Up Code
An asm block inside a top-level when start handler runs once when the program boots, before the very first television frame begins. Unlike ordinary blocks whose labels are private, labels defined in a when start handler stay visible to every asm block written on later lines—making when start the natural home for shared data tables, persistent .byte variables, or helper subroutines that several handlers call with jsr. (Visibility still flows downward, so a block written above when start cannot see its labels.) The compiler counts calls to bounded helpers automatically, while keeping the startup handler's own work outside the frame budget.
var seen: Number<u8> = 0
when start
asm
jmp done
ticks:
.byte 40
bump_ticks:
inc ticks
lda ticks
sta seen
rts
done:
end
end
when System.screen.frame
asm writes(seen)
jsr bump_ticks
end
end
System.screen.border <- Color(seen % 16)Keep cycles(...) on the calling block when a helper's cost is unknown. A declaration on the startup block alone does not price calls into it. The compiler refuses automatic pricing for unresolved calls, unbounded loops, recursive calls, escaping control or unbalanced returns. Counted helpers still have to fit the complete frame. Interrupt routines keep their existing restriction on calls to shared startup helpers.
Start-Up Code in a Case
When you write a when start handler inside a case (match arm), it runs on that case's opening frame each time the program enters the case—so its cycle cost is counted as part of that opening frame's budget. While the top-level when start runs before frame timing begins (and can therefore hold an uncounted hardware-wait loop prior to its first wait), a case's when start runs inside a live frame and requires bounded loops or a cycles(...) clause (frameUnbounded). Labels declared in a case's when start are visible to asm blocks below it within that same case (and any sub-cases nested inside it), and invisible outside the case (assemblyUnknownName). That means sibling cases can freely reuse the same label names without colliding; if two cases want to share a labeled cell, declare it in a top-level when start above the match.
Any labeled .byte cell inside a case that gets modified by an asm block is automatically reset to its initial .byte value each time the case starts—just like a case-local var. Adder resets those cells before enabling the case's interrupt routines and before running the case's when start, so an interrupt never sees leftover data from a previous visit to the case. By contrast, a labeled cell declared at the top level outside every case is initialized once at boot and keeps its value across case changes.
var f = false
var seen: Number<u8> = 0
when System.joystick[2].fire.pressed
f = not f
end
System.screen.text[0][0..<3] <- seen.digits(3)
match f
true ->
when start
asm
jmp done
laps:
.byte 40
done:
end
end
when System.screen.frame
asm writes(seen)
inc laps
lda laps
sta seen
end
end
false ->
const m = 1
endInterrupt Routines
Want to split scroll registers mid-screen, multiplex sprites, or run a high-frequency sound routine on a hardware timer? In Adder, a hardware interrupt routine is simply a when handler for System.screen.interrupt(line: n) or System.clock.interrupt(...) whose body may mix checked Adder statements and asm blocks in source order. System.screen.interrupt(line: n) triggers the instant the VIC-II raster beam reaches picture row n (a compile-time whole number from -51 to 210 on every standard). It uses the same origin as color bands and sprites. You write just the heart of the routine: the compiler wires up the interrupt vectors for your program's memory map, preserves the registers (A, X, Y) used by the complete body and its calls, acknowledges the hardware interrupt flag, and emits the return from interrupt when execution reaches end.
Here is a complete raster interrupt that flips the border color at picture row 49 of every frame:
var level: Number<u8> = 3
when System.screen.interrupt(line: 49)
asm
inc ticks
lda level
sta System.screen.border
ticks:
.byte 0
end
endBecause execution falls through end into the compiler's register-restore and rti sequence, your block must not terminate the interrupt on its own: writing rti, brk, or jumping out of the block is caught with interruptRoutineForm. The interrupt header has no event filter or fast/small mark, and its assembly blocks have no writes(...) clause (interruptRoutineForm). Put conditions inside the body. Fixed local declarations use const; mutable local calculations use var. Both initialize when reached on each invocation. Guards leave through the compiler's interrupt cleanup, and bounded loops keep their ordinary semantics.
var level: Number<u8> = 3
when System.screen.interrupt(line: 49)
const sampled = level
var shade: Number<u8> = 0
for i in 0..<3
shade = shade +% 1
end
guard sampled < 16
System.screen.border = Color(shade)
asm
inc ticks
ticks:
.byte 0
end
endAn interrupt may mutate its own locals, including local records and lists, and call ordinary value functions whose complete call chains are safe. It cannot change an outer variable, field, element, binding, input snapshot or outer mutating receiver. Shared reads see the stored value at execution; a multi-byte read is not a coherent snapshot. Waits, temporal operations, work/queue services, drawing and printing are refused at the operation or call path (interruptUnsafe). Arbitrary assembly functions are also refused as interrupt callees.
Publications let foreground code offer one complete ordinary value to native readers. Read .current into a local when its fields belong together. publish(value) runs in foreground code.
Interrupt = writes an admitted scalar chip register immediately. Built-in border/background and volume outputs work this way; row/column choices retain their ordinary constant restrictions. A scalar typed chip mapping, such as register: Color at 0xD020, also accepts register = Color.red. Normal nominal and boundary checks still apply. This creates no output binding or foreground recalculation: a later foreground binding can overwrite the register. Mapped RAM, composite screen/sprite outputs, banking and control registers reserved for the compiler remain refused. Ordinary foreground code drives these outputs with maintained <- bindings outside handlers.
A helper with mut parameters may change an interrupt invocation's own local var, field or element. Passing an outer place is interruptWrite. Each raster or timer calculation has separate mutable-call descriptors and helper storage, including when a timer interrupts a raster helper. The publish value statement belongs only to a work body; Publication.publish(value) belongs to foreground code, so neither runs inside an interrupt.
Multiple assembly blocks have separate labels and trust declarations. Their .byte cells retain program or case lifetime; Adder locals belong to each invocation. A cycles(...) clause applies only to its block. A mixed body cannot restore an uncontrolled interrupt mask with plp, enable nesting or jump between assembly blocks and generated statements. A single runs(n) rearming block must be reached once on every normal path: it cannot be conditional, repeated in a loop, or skipped by a guard. Its run count charges the entire invocation.
Generated calculations preserve foreground temporaries and supported helper workspaces. A timer can interrupt raster work; the timer's active body masks its source, and the frame watchdog uses the same isolated context. Registers, scratch and the interrupted numeric mode are restored on normal return. If a numeric, index or conversion check fails, sources are disabled before shared failure services: earlier completed effects remain, the failing and later stores do not run, and the authored failure line is reported.
Every interrupt routine is included in the compiler's frame-budget check: the compiler counts local initialization, reached calls, preservation and every assembly block in each run (plus setup and return overhead), as Work Without a Limit describes for any block, and displays the cost right next to the when line in the cost report. If your interrupt block contains a loop the compiler cannot bound automatically, add a cycles(...) clause on the asm line just like in any other block.
Installing by Hand
Why does Adder manage the interrupt vectors and control registers itself? Depending on whether your program uses text mode, a bitmap canvas, or cases that switch banks and ROMs, the active interrupt vectors live at different addresses ($0314–$0319 vs. $FFFA–$FFFF) and coordinate with the frame loop and color bands. To keep a manual poke from pulling the rug out from under the runtime, the compiler blocks direct stores to the interrupt vectors ($0314–$0319, $FFFA–$FFFF), the interrupt flag and enable registers ($D019, $D01A, $DC0D, $DD0D), and—except inside a self-scheduling runs(n) routine—the raster compare register $D012 (interruptInstall). When checking indexed stores like sta base,x, the compiler tracks the range of X if you load it with a constant and only decrement it, and otherwise conservatively checks all 256 possible offset addresses.
So if you are porting a classic routine that pokes $0314/$0315 and ends with jmp $ea81, simply drop the setup boilerplate and put the body instructions inside when System.screen.interrupt(line: n)!
What a Routine May Touch
Because a hardware interrupt can fire between any two instructions of your main program, an interrupt routine follows strict rules to avoid corrupting work in progress:
- An assembly block may write only to hardware chip registers and to its own labeled
.bytecells (by name). Writing to an Addervaror binding—or storing indirectly through a pointer—is flagged withassemblyInterruptWrite. - It may read any Adder variable, binding, constant, or memory address (including through a pointer).
- Because the main program may be right in the middle of using
scratch($FB–$FE) when the interrupt hits, an interrupt routine may not touchscratchby name or address (assemblyInterruptScratch). - The stack must stay balanced: every
pha/phpinside the block must have a matchingpla/plpon every path, andtxsis forbidden (assemblyInterruptScratch).
If your interrupt routine uses adc or sbc and any block in the program ever sets decimal mode with sed, the compiler automatically inserts a cld at the top of the interrupt routine so an interrupt arriving mid-sed never adds in BCD by accident.
The compiler also optimizes main-program variables around your interrupts: if an interrupt routine reads an Adder variable, the compiler makes sure every update to that variable is written straight through to its memory cell; if your interrupt reads no Adder variables, the optimizer has full freedom to keep values in registers.
Routines That Pick Their Own Lines
Advanced raster routines—like a sprite multiplexer or a wobbling raster bar—often compute and store their next trigger scanline into $D012 on the fly. To write a self-scheduling raster interrupt, add runs(n) on the opening asm line to declare the maximum number of times the routine will fire per frame. The line: number in when System.screen.interrupt(line: ...) sets the initial trigger line at start-up, and from then on your block writes a hardware raster line to $D012 at the end of each pass to schedule the next run (including wrapping back to the top line for the next frame).
Here is a self-scheduling routine that fires 3 times per frame to paint red, white, and blue border splits at moving scanlines top, top + 40, and top + 80:
const red = Number<u8>(Color.red)
const white = Number<u8>(Color.white)
const blue = Number<u8>(Color.blue)
top: Number<40..<100> <- System.screen.frame.every(20).cycle()
when System.screen.interrupt(line: -50)
asm runs(3)
ldx step
lda colors,x
sta System.screen.border
inx
cpx #3
bne arm
ldx #0
arm:
stx step
lda top
clc
adc offsets,x
sta $d012
step:
.byte 2
offsets:
.byte 0, 40, 80
colors:
.byte red, white, blue
end
endBecause the compiler cannot predict which scanlines your code will write to $D012 at run time, it multiplies the routine's worst-case single-run cost by n and charges that total to the frame budget, marking the line with * in the cost report. Storing to $D012 without declaring runs(n) is flagged with interruptInstall, while declaring runs(n) on a block that never writes $D012 (or on a non-interrupt block) is flagged with interruptRuns.
A self-scheduling runs(n) routine claims the VIC-II raster interrupt for itself while active, so it cannot share the same scope with color bands or with other raster interrupt routines (rasterOwner).
Fixed-line raster routines (without runs), by contrast, can share the screen with color bands and with other fixed-line routines: the compiler sorts all of them by scanline and chains each interrupt into the next. If a fixed-line routine takes so many cycles that the electron beam would already pass the next scheduled raster line before the routine finishes and arms it, the compiler catches the collision at build time with interruptOverrun.
Routines on a Timer
System.clock.interrupt(ms: n) (or seconds:) runs your complete checked body repeatedly on a constant hardware timer period of up to 64 milliseconds (interruptPeriod if out of range), calibrated so the time between interrupts is identical on PAL and NTSC hardware. The routine runs on CIA 2 Timer A (wired to the 6510's NMI line) and ignores the RESTORE key. To protect the timer, no other asm block in the program may write to CIA 2 Timer A's registers or read the interrupt flag register at $DD0D (interruptInstall), since reading $DD0D clears the hardware flag. On a real Commodore 64, holding down the RESTORE key at the exact cycle the timer underflows can mask the NMI edge; Adder's frame loop automatically checks for a stuck timer flag once per frame and services one missed run so the timer keeps ticking (and includes that recovery run in the frame budget).
when System.clock.interrupt(ms: 10)
asm
inc ticks
ticks:
.byte 0
end
endIn the frame budget, the compiler charges each frame with the maximum number of timer ticks that can fall inside one frame (floor(frame_cycles / period_cycles) + 1). If the routine's own worst-case execution time is not strictly shorter than its timer period, the next interrupt would arrive before the previous one returned, so the compiler catches that with interruptSlow. Because the machine has one CIA 2 Timer A for timer interrupts, two timer interrupt routines can live in different cases, and the compiler flags two that would be active at the same time with interruptTimer.
What a Routine's Stores Add to the Frame
Because an interrupt routine can write directly to VIC-II registers, the compiler also accounts for any extra video-chip bus cycles those register writes can cause:
- Storing to a color register, horizontal scroll (
$D016), memory pointers ($D018), or a sprite's X coordinate, shape pointer, or color adds 0 extra bus cycles. - Storing to sprite enable (
$D015), sprite Y expansion ($D017), or a sprite's Y coordinate can make that sprite visible on additional scanlines, so the compiler conservatively budgets that sprite's 2-cycle DMA fetch across every line of the frame. - Storing to
$D011(which holds the 3-bit vertical scrollYSCROLL) can trigger an extra character-row badline fetch if it matches the low bits of the current scanline, so the compiler adds 43 cycles (one badline) for each$D011store a run can execute. - Writing to a register whose timing impact cannot be bounded statically—such as the processor banking port
$01—is flagged withframeUnbounded.
Routines in Cases
When you declare an interrupt routine inside a case, Adder automatically enables it when the case starts and switches it off when the case ends—so inactive cases add zero cycles to other cases' frames. Any labeled .byte counters inside the routine reset cleanly each time the case starts, as described in Start-Up Code in a Case. Pressing RUN/STOP or hitting a range-overflow stop cleanly shuts off all active interrupt routines before returning or halting.
Memory
Every Adder program loads at the standard Commodore 64 BASIC start address $0801, with machine code, tables, and variables laid out upward from there. The bottom line of the cost report shows your program's total byte size, and if code and data ever grow past $CFFF into the $D000 I/O area, the compiler lets you know with outOfMemory.
By default, the 1,024-byte text screen sits at $0400–$07FF (unless a bitmap canvas or case layout moves it to another VIC bank). Inside assembly, writing System.screen.text always resolves to the active screen's base address automatically.
Placed Values
Need a buffer or lookup table at a specific, fixed hardware address—say, in the free 4 KB RAM block at $C000–$CFFF? A placed value declared with at 0xC000 sits at that exact address, and both your high-level Adder code and your asm blocks can read and write it by name:
tiles: [16 of Number<u8>] at 0xC000
when System.screen.frame
asm
ldx #15
fill:
txa
sta tiles,x
dex
bpl fill
end
end
System.screen.border <- Color(tiles[3] % 16)To save you from mysterious memory collisions, the compiler checks the address span of every placed list against the rest of the memory map:
- overlapping the 6510 processor port at
$00–$01is flagged withplacedOnPort; - overlapping your compiled program code and variables is flagged with
placedOverProgram; - overlapping another placed list is flagged with
placedOverList; - overlapping compiler zero-page variables, the hardware stack (
$0100–$01FF), or the interrupt vectors is flagged withplacedOverRuntime; - overlapping a bitmap or sprite picture asset is flagged with
placedOverPicture; - overlapping the text screen is flagged with
placedOverScreen(unless that placed list is intentionally bound as the screen itself).
A single scalar placed value (one byte or word, often used for a custom hardware register) is checked only against program memory and other placed values, leaving you free to point it at memory-mapped hardware.
Memory a Block May Not Use
Adder keeps your program's variables and runtime state in zero page from $02 to $8F, assigning addresses automatically on each build. A program without assembly, mapped hardware or linked libraries can also use unused KERNAL workspace in $90–$F6 and $F9–$FA when its repeated frame work needs more cells. Disk calls keep their workspace reserved; programs combining disk calls with interrupts retain the ordinary region.
An asm block may read $02, and it has full use of scratch ($FB–$FE), while writing to $02 or touching any zero-page address from $03 through $8F directly is caught with assemblyZeroPage (including indexed instructions like lda $80,x whose reach overlaps $03–$8F). When your program starts from BASIC, Adder saves the state it must return to BASIC and restores it if the program stops. Extra KERNAL scratch needs no save when the ROM replaces it before reading it again.
In a program that uses a bitmap canvas, the runtime configures the 6510 banking port ($01), the VIC-II memory bank ($DD00), the hardware interrupt vectors ($FFFA–$FFFF), and CIA 1 Timer B ($DC06, $DC07, $DC0F) at start-up to manage frame timing and drawing. In such a program, writing to any of those addresses from an asm block is blocked with bitmapAssembly.
Similarly, when a program switches between text and a bitmap canvas across cases (or between two different canvas modes), it runs with the BASIC and KERNAL ROMs banked out ($01 set to $35) so RAM underneath the ROMs is accessible. In those programs, calling or jumping into the ROM address ranges ($A000–$BFFF or $E000–$FFFF) or writing to the KERNAL RAM vectors at $0314–$0319 is caught with romAssembly.
Standalone Assembly
What if you want to write a pure 6510 assembly program from scratch—a tiny demo intro, a custom loader, or a standalone machine-code experiment—with no Adder runtime at all? The compiler has a dedicated --asm mode built right in:
adder compile --asm border.s -o border.prgThis assembles border.s into border.prg and writes a companion VICE symbol file border.lbl right next to it (if you leave off -o, both files are written alongside the .s source file, and if assembly fails, any existing output files are left untouched).
In --asm mode, the compiler uses the exact same 6510 instruction encoder as asm blocks, with zero inserted runtime and zero optimizer rewrites—every single byte in the .prg comes straight from your .s file. By default the origin starts at $0801 (and must finish below $D000), so if you want to launch your program from BASIC with RUN, start your file with a 12-byte BASIC SYS stub:
; Set the border to light blue and return to BASIC.
BORDER = $d020
.byte $0b, $08, $0a, $00, $9e, '2', '0', '6', '1', 0, 0, 0
start: lda #14
sta BORDER
rtsThose twelve .byte values form the tokenized BASIC line 10 SYS 2061, which jumps straight to $080D (2061 in decimal), where start: begins.
Standalone .s files also unlock a full macro-assembler toolkit beyond what inline asm blocks need:
- comments can start with either
;or//; - numbers accept decimal,
$hex,0xhex, or0bbinary, and%acts as the modulo (remainder) operator in expressions; NAME = expressionand.setdefine symbolic constants using full arithmetic, bit shifts, bitwise operators, comparisons, parentheses, and</>byte extractors;z:ora:before an operand forces 8-bit zero-page or 16-bit absolute addressing;.byte,.word,.ascii,.space count, fill,.balign, and.sectionlay out data and code sections;.macro/.endm,.rept/.endr, and conditional assembly (.if,.else,.endif,.ifndef,.error) expand at assembly time, while numbered local labels (1:referenced with1fforward and1bbackward) keep short loops tidy.
In a standalone .s file, the whole 64 KB address space is yours to manage; the assembler simply verifies branch distances and guards against the unstable and JAM opcodes.
Callable Byte Libraries
Callable libraries are a work in progress.
A compiled .addl file carries its public functions and machine code together. An Adder application imports the file, calls its functions, and builds one ordinary .prg. The compiler chooses addresses and initializes each used library before the application's first calculation.
Build and Share a Compiled Library
Use the installed adder CLI for every step. In a new folder, save this as math.adder:
export fn add_one(n: Number<u8>): Number<u8>
n +% 1
end
export fn add_two(a: Number<u8>, b: Number<u8>): Number<u8>
a +% b
endBoth functions accept every byte from 0 through 255. The +% operator wraps; add_one(255) returns zero. Build and inspect the library:
adder compile --library math.adder --name math --library-version 1.0.0 -o math.addl
adder inspect math.addl
adder inspect math.addl --jsonThe ordinary inspection lists add_one(n: Number<u8>): Number<u8> and add_two(a: Number<u8>, b: Number<u8>): Number<u8>, their module identity, and unplaced image, private RAM, zero-page and stack requirements. Cycle figures are estimates until the application chooses final addresses. --json prints the complete checked manifest. Inspection reads the artifact without running it. A function signature describes its parameters and result; it is not a cryptographic signature or a private debugging label.
Create a separate folder named consumer and copy only math.addl into it. The authoring source and generated sidecars are not needed. Save the following as consumer/main.adder:
import "math.addl" as Math
var one: Number<u8> = Math.add_one(n: 41)
var two: Number<u8> = Math.add_two(a: 20, b: 22)
System.screen.border <- Color(one % 16)
System.screen.content <- [Text("ONE: \(one) TWO: \(two)").at(row: 3, col: 2)]Build the application and ask for its costs:
adder compile consumer -o consumer.prg
adder costs consumerRun consumer.prg in a C64 emulator or on a C64. The display reads ONE: 42 TWO: 42. Its sibling consumer.lbl includes the module's public labels. No address flags, copied bindings, or manual initialization are needed. Disk and cartridge builds link the same library into the boot program; the .addl input is not copied onto the disk as a runtime data file.
The Lab's Compiled math project is a complete example with a distributed artifact, both calls, and a counter you can change with Space and Return. Upload or archive the whole project to keep its library bytes. Opening the .addl file in the Lab shows its interface. VS Code offers its public members, labels and results through the same project language service.
Imports and Calls
Write import "lib/math.addl" as Math at top level before its use. The alias is a namespace for public functions. PascalCase aliases are a useful convention; they do not create values or types. Paths resolve from the project root, including imports in an included source. Source include still inserts source into the shared namespace.
The first byte ABI admits stateless total functions with one or two full-range Number<u8> parameters and one Number<u8> result. Named arguments may be written in either order. Each argument is evaluated and checked once, in written order, before the call. Foreground functions, bindings, handlers and bounded work can call imported functions under their ordinary rules. Fixed-list arguments use ordinary function lifting. Bare imported function references, callbacks, library-to-library imports and interrupt calls are refused.
You can rename a file or choose another alias without changing its embedded module name. Equal copies of the same module share one linked instance and initializer. Different versions or different bytes with the same embedded name are refused together. Every import is validated, including an unused one; a valid library with no reachable calls adds no target code.
Keep exported source total and stateless as described in Callable Byte Exports. A source wrapper remains an ordinary source function with its usual checks. The compiler chooses final memory and zero page, includes initialization and call setup in the application's costs, and repeats initialization on normal restart. Treat a compiled artifact as executable code from its author; structural checks and bounded compiler analysis do not certify arbitrary machine code.
Advanced: Fixed Placement for an Assembly Caller
An export fn can be built into a returning library for an independent assembly caller. The library call takes argument one in A and argument two in X, and returns its byte result in A. Call adder_init after loading and before the first export. Initialization returns, can be repeated, and writes only private RAM. It performs no screen, sound, CIA or KERNAL setup.
Save the add_one and add_two functions from Callable Byte Exports in library.adder. Build the library with the installed adder CLI:
adder compile --library library.adder \
--origin 0x4000 --limit 0x5000 --ram-origin 0x6000 --ram-limit 0x6100 \
--zero-page-from 0xfb --zero-page-to 0xfe -o library.prgAll six placement flags are required. Code and private RAM use exclusive limits; zero-page endpoints are inclusive and reserved with saved=false. Code and RAM must each lie in $0800-$9FFF or $C000-$CFFF and their supplied reservations must be disjoint. Zero page must lie wholly in $02-$8F or $FB-$FE, include all fixed scratch bytes used by the generated helper, and belong exclusively to this library. Insufficient or unsupported ranges are refused. The pilot emits PRG only and rejects assembly/media mode conflicts and input overwrites.
The four outputs are .prg, public .lbl labels, .inc.s numeric constants and an ABI-v1 .abi.json manifest. The manifest contains final addresses, source signatures, code/data/private RAM/zero-page ranges, clobbers, maximum additional hardware-stack bytes including the public JSR return address, and static call and initialization costs. Costs include JSR through RTS and exclude DMA or interrupt delays. Rebuild bindings after each library build; private compiler labels are not a supported interface.
A caller must clear D before a call, keep code/data/private RAM visible, reserve the reported stack capacity and serialize calls and initialization. X/Y and N/Z/C/V may change. I, clear D and the $00/$01 banking state remain unchanged. IRQ/NMI handlers must preserve registers, avoid reserved memory and never invoke the library. There is no reentrancy or interrupt-call ABI.
To make a caller, copy the generated library.inc.s definitions above the following code in caller.s. The CLI currently reads one assembly file; it does not import the bindings automatically. The definitions supply addresses, not the library's machine code.
.byte $0b, $08, 10, 0, $9e, $32, $30, $36, $31, 0, 0, 0
start:
cld
jsr adder_init
lda #41
jsr adder_add_one
sta $0400
lda #20
ldx #22
jsr adder_add_two
sta $0401
rtsBuild that combined file with the same CLI:
adder compile --asm caller.s -o caller.prgLoad both library.prg and caller.prg at the addresses in their PRG headers, then run SYS 2061 from BASIC. The caller writes 42 to each of the first two screen cells and returns. Replace the copied definitions whenever you rebuild the library, since its call addresses can change.
Region scroll registers
A 24-row scrolling terrain uses a raster service at picture row 191. The service saves A, acknowledges $D019, waits 36 cycles and restores $D016 to $08 for a still, 40-column HUD. The linked code takes 51 cycles through the store and 60 through its return; the processor needs another 7 cycles to start the interrupt. The late bound adds 9 cycles for the interrupted instruction, including a taken branch that delays the interrupt poll. The compiler proves both edges of the border window on every supported standard; the cost chapter lists the bounds and VICE observations.
At startup, CIA 2 timer A runs once with a zero latch and $DD0E = $19. Its interrupt mask is $81 at $DD0D. The program never reads $DD0D afterward, so the interrupt holds NMI low and RESTORE cannot produce another edge at the seam. Setup takes 25 bytes and 34 processor cycles. The first NMI still uses the KERNAL's bare return through $0318 and costs 20 cycles, included in startup. Timer and disk services cannot use that timer at the same time.
Sprite slots 0–2 fetch near the end of a line; slots 3–7 fetch near its beginning. The compiler requires their complete vertical bounds to exclude the service line and its two neighbors, including bus handover. It refuses unproved DMA overlap, authored register writers and operations that can release the NMI latch. The font's ordinary final pixel rows can remain visible.
Diagnostics
Adder reports syntax, type and resource errors before building the program. A changing number that cannot be proved to fit its destination instead gets a runtime check; if that check fails, the running program stops and names the source line. Warnings, such as an admitted slower update, explain a limitation while still allowing compilation. Every compiler message has a short key that names the rule, such as wrongType. This chapter gathers every diagnostic key in one place, grouped by the part of the language it helps you with.
Each message starts with a clear one-line summary, followed by the rule behind it and, whenever possible, a ready-to-use Fix: written in Adder using your own variable names. Because the compiler speaks in terms of the names and numbers in your code, two programs that hit the same rule will see their own details in the message.
Below each key, you will find a sample one-line summary (Message: ...) and a link to the handbook section where you can read more and see working examples. The final two sections list the handful of keys that only show up in huge programs, and the keys kept as internal safety nets.
Reading a Program
protocolUse
Message: Use protocol Located as a parameter type.
A stored value needs its concrete type. See Protocols.
protocolConformance
Message: Empty does not satisfy Located.
The details name each missing or incompatible requirement. See Protocols.
protocolDeclaration
Message: No protocol called Missing has been declared.
Declare the protocol before its conforming types and keep each requirement distinct. See Protocols.
scrollView
Message: The compiler cannot prove this scroll view.
The details name the missing backing content, boundary window or interference bound, including sprite DMA that can overlap the scroll seam. A fixed machine font is admitted. See Scroll and Window.
Before checking types or ranges, the compiler reads the raw text of your program—its characters, literals, brackets, and line breaks. These messages help you fix syntax hiccups right away.
badCharacter
Message: @ is an invalid character: Adder doesn't use it.
Source Text explains this message.
directionControl
Message: U+202E is a hidden text-direction control, and Adder doesn't allow it anywhere in a file.
Comments explains this message.
badNumber
Message: 1_000 is not a number Adder understands.
Whole-Number Literals explains this message.
reuContract
Message: A Reu is discovered through System.reu; it cannot be constructed.
Check the optional device and its capacity, then transfer contiguous byte windows, or rows of a fixed byte matrix, with the explicit destination mark. The one list of Color a fetch may fill is the list bound to System.screen.color. See RAM Expansion Units.
stringContract
Message: String length 2 exceeds capacity 1.
String capacities and adapter widths must be fixed whole numbers within their documented bounds. A value must fit its destination capacity. Length and capacity are read-only; use append, insert, remove, clear or truncate to change the live value. See bounded strings.
badEscape
Message: A backslash in text can open an interpolation with an opening parenthesis or escape a quote or backslash, not t.
String Literals explains this message.
unterminatedString
Message: This text starts with a quote mark but never ends.
String Literals explains this message.
stringNotPrintable
Message: The Commodore 64 screen has no glyph for "é" (U+00E9).
String Literals explains this message.
lineEndsInBracket
Message: This line ends inside the (.
Lines explains this message.
unexpected
Message: This line stops too soon.
Lines explains this message.
reservedName
Message: at is a reserved word and cannot be used as a name.
Choose another name for the parameter or declaration, such as position. See Lexical Structure.
missingEnd
Message: This when block needs an end.
Lines explains this message.
strayEnd
Message: end has nothing to close.
Lines explains this message.
nestingExpression
Message: Brackets are nested more than 16 deep here.
Lines explains this message.
nestingType
Message: This type nests lists more than 16 deep.
Lists explains this message.
rangeNeeded
Message: A range was expected after the first number, not 1.
Range Bounds explains this message.
numberNeeded
Message: A number was expected here, not +.
Range Bounds explains this message.
arraySizeNeeded
Message: The size of a list must be a number, a constant's name or constant arithmetic in parentheses, not "a".
Lists explains this message.
typeNeeded
Message: A type was expected here, not =.
Variables explains this message.
resultTypeNeeded
Message: double needs a result type.
Parameters and Results explains this message.
parameterNeedsType
Message: The input a doesn't say what kind of value it takes.
Parameters and Results explains this message.
addressNeeded
Message: A memory address, as a number, was expected after at, not x.
Placing a Value in Memory explains this message.
assignmentNeeded
Message: x needs a declaration or binding.
Assignment explains this message.
actionNeeded
Message: <- can't follow here: a when handler holds updates and actions.
Handlers explains this message.
typeNeedsBrackets
Message: Number<u8> is a type, so it needs a value in brackets to convert.
Number Conversions explains this message.
chainedComparison
Message: A comparison can't be chained with another one.
Operators and Their Order explains this message.
parenthesize
Message: Ranges and ?? can't be mixed without brackets.
Operators and Their Order explains this message.
numberMember
Message: A number needs parentheses before a .: (3.5).
Members explains this message.
structColon
Message: This struct field needs a colon.
Struct Blocks explains this message.
structLabel
Message: 2 can't start a struct field.
Struct Blocks explains this message.
includeNeedsName
Message: include must be followed by a file name in quotes.
Include and Project Files explains this message.
textNeeded
Message: .text must be followed by some text in quotes.
Data explains this message.
ifNeedsThen
Message: An if needs then after its condition.
If Statements explains this message.
inlineIfLine
Message: An if ... then that starts its answer on the same line ends on that line.
One-Line Form explains this message.
statementAfterArm
Message: This line already has its whole body after the ->.
Match Statements explains this message.
dottedArm
Message: A line of a match names its case without a dot, so .b is written b.
Patterns explains this message.
Compile-Time Directives
Source assertions check fixed relationships before any target work runs. A timing directive chooses whether bounded ordinary work may take more than one refresh. Malformed spelling, missing conditions and missing literal explanations retain the ordinary reading diagnostics above.
assertionFailed
Message: The pod must reach the clamp.
A valid fixed Boolean condition is false. The summary is the explanation written in the directive; the next line identifies its condition. Change the constants or correct the relationship. See Compile-Time Assertions.
assertionExpression
Message: This assertion needs a fixed numeric or Boolean expression.
The condition uses a form outside the supported fixed arithmetic and Boolean forms, such as a call or member access. See Compile-Time Assertions.
assertionConstant
Message: limit is not a fixed Number or bool constant for this assertion.
Use a preceding numeric or Boolean constant. Variables, reactive bindings and named hardware or enum values cannot supply this check. See Compile-Time Assertions.
assertionBoolean
Message: This assertion needs bool, but its condition is Number<0...255>.
Write a comparison or another Boolean condition; a number is not a truth value. See Compile-Time Assertions.
assertionLimit
Message: This assertion expression is too large to check.
A condition may hold at most 128 expression parts and reach depth 32. Name smaller fixed calculations before the assertion. See Compile-Time Assertions.
allowSelector
Message: #allow teleport is not a supported timing directive.
The supported choice is #allow frame_skips. See Allowing Slower Updates.
frameSkipsPlacement
Message: The timing directive must be the first non-comment statement.
Write the directive once at the start of the main source, before includes and other statements. A repeated directive or one inside an included source is also refused, with a summary naming that placement. See Allowing Slower Updates.
frameSkipsUnsupported
Message: Slower updates cannot retain the timing guarantee for the output System.screen.columns.
The program needs more than one refresh and also uses a service whose deadline still applies. Reduce the work or spread it across updates with supported tools. A fitting program may use the same service with the directive present. See Allowing Slower Updates.
frameSkipsUnproved
Message: The compiler cannot prove a finite bound for this slower update.
The complete work or boundary wait lacks a supported exact bound. Even bounded loops can multiply their turn counts beyond the cycle-count range the compiler can represent. The detail names the failed proof; this remains a refusal rather than a successful build with a warning. See Allowing Slower Updates.
directivePlacement and directiveLine
The line reader reports these keys when a directive appears inside a body or tries to continue onto another physical line. Keep directives at unconditional top level and keep each condition and literal explanation on its directive's line. See Source Directives.
Names and Declarations
These messages help you keep names clear and distinct across constants, variables, reactive bindings, functions, op declarations, and hardware outputs.
builtinName
Message: Color is a built-in type, so a declaration can't use that name.
Names explains this message.
capitalizedDeclaration
Message: Capitalized names belong to types; Speed cannot be declared here.
Names explains this message.
internalName
Message: __count begins with two underscores, which the compiler keeps for names of its own.
Names explains this message.
lookalikeNames
Message: сор looks the same as cop, which is already a different name.
Names explains this message.
symbolCollision
Message: gröe and gr_u00f6_e would both become gr_u00f6_e in the finished program.
Names explains this message.
unknownName
Message: hue isn't declared here yet.
Names and Scope explains this message.
duplicateDeclaration
Message: x is already declared.
Names and Scope explains this message.
duplicateParameter
Message: This function has two inputs called a.
Parameters and Results explains this message.
shadowing
Message: limit is already a constant.
Names and Scope explains this message.
unknownFunction
Message: f isn't a function Adder knows.
Functions explains this message.
unknownType
Message: foo isn't a type.
Type Declarations explains this message.
constantChanges
Message: best can't be declared with const, because score changes while the program runs.
Constants explains this message.
eventConstant
Message: An event happens over time and cannot be a constant or a variable.
Events explains this message.
selfAssignment
Message: n = n gives the value back to itself.
Assignment explains this message.
unreadDeviceName
Message: border is declared here, but nothing reads it.
Naming a Device explains this message.
resultUnused
Message: The result of twice(3) is never used.
Calls and Device Actions explains this message.
recursion
Message: f can't call itself.
Functions explains this message.
functionSets
Message: A function cannot change g, which belongs to the program.
What a Function May Read explains this message.
operationScope
Message: A function cannot read the program's bonus directly.
What a Function May Read explains this message.
randomImpure
Message: random gives a new answer every time, so a function can't use it.
What a Function May Read explains this message.
functionBodyValues
Message: A function's body is made of values, and this line is something else.
Statements in Functions explains this message.
localImmutable
Message: value already has a value in this body and can't be assigned again.
Statements in Functions explains this message.
valueBlockEmpty
Message: This block holds no value.
Parameters and Results explains this message.
bindingBodyEffect
Message: A binding body calculates a value and changes only its own locals.
Calculations in a Binding Body explains this message.
bindingClock
Message: This binding needs an admitted execution clock and a complete available value.
Binding Execution Clocks explains the producer, consumer and clock checks. The detail names the unavailable value, unsupported clock or reader window that prevents this use.
memberNeedsOwner
Message: Spot.show needs the value it belongs to as its first input.
Member Functions explains this message.
memberOverlap
Message: These members share a name on the same type.
Member Functions explains this message.
parameterAgreement
Message: The parameter T needs one type or length.
Type Parameters explains this message.
parameterTypeName
Message: X is a type parameter.
Type Parameters explains this message.
opHolds
Message: total_of cannot hold a variable declared with var.
Ops explains this message.
loopInOp
Message: f is an op, and an op cannot hold a loop.
Ops explains this message.
opControlParameter
Message: reset names an op instance control, so it cannot be an op parameter.
on: and reset: explains this message.
operationBody
Message: End empty with the value its op returns.
Ops explains this message.
memoryOutsideBinding
Message: cycle remembers earlier values, so it only makes sense in a <- line.
Remembering With previous explains this message.
loopMemory
Message: i.sum() keeps a memory for the line that calls it, and a loop would run that line once for each turn.
Loops and the Frame explains this message.
recurrenceNeedsFrom
Message: ticks reads its own previous value, so previous needs from:.
Destination and start explains this message.
forwardNeedsFrom
Message: b is declared further down, so previous needs from:.
A Binding That Reads Itself explains this message.
forwardNeedsType
Message: behind is read before its line, so it needs a declared range.
A Binding That Reads Itself explains this message.
recurrenceNeedsType
Message: x reads its own previous value, so it needs a declared range.
A Binding That Reads Itself explains this message.
bindingLoop
Message: tick reads itself in the same frame.
A Binding That Reads Itself explains this message.
overlap
Message: An earlier declaration already sets this destination.
Outputs explains this message.
notAnOutput
Message: a isn't something the program can draw to.
Outputs explains this message.
bindingNeedsOutput
Message: A <- line like this must say which part of the screen it sets.
Outputs explains this message.
functionBinding
Message: f is a function, so a binding cannot target it.
Output Declarations explains this message.
outputBody
Message: An output body holds bindings or assembly.
Output Declarations explains this message.
outputTarget
Message: v is not an output this body can bind.
Output Declarations explains this message.
outputState
Message: An output cannot write n.
Output Declarations explains this message.
includeMissing
Message: The project has no file lib/world.adder.
Include and Project Files explains this message.
Types and Ranges
These messages appear when a type or number range doesn't match the values you give it, helping you catch out-of-bounds numbers before the program ever starts.
numericFormat
Message: i32 is not a numeric storage format.
Storage Formats explains this message.
rangeEmpty
Message: The range 5...1 holds no numbers.
Range Bounds explains this message.
rangeEndNotFixed
Message: widest is not known before the program runs, so a range cannot end at it.
Range Bounds explains this message.
rangeFixedBounds
Message: width - 1 is a calculation, and a range ends at a number, a member, a constant name or constant arithmetic in parentheses.
Range Bounds explains this message.
rangeBoundLimit
Message: A range endpoint can contain at most 128 expression nodes and have depth 32.
Range Bounds explains this message.
rangeNeedsFixedIntegers
Message: A range of values needs whole numbers at both ends, written out.
Range Bounds explains this message.
rangeLength
Message: This range holds too many or too few numbers.
Range Bounds explains this message.
rangeDoesNotFitType
Message: The range 0...60 doesn't fit in a Color.
Narrowed Named Sets explains this message.
rangeOnStruct
Message: A range cannot follow a Point.
Narrowed Named Sets explains this message.
rangeNoRepresentation
Message: both can reach 0 to 131,070, wider than any number holds.
Results and Their Ranges explains this message.
literalDoesNotFit
Message: level allows 0 to 0.996, but this value is 0.999.
Fractions explains this message.
constantOutOfRange
Message: 300 doesn't fit in the allowed range 0 to 255.
Values Outside a Range explains this message.
fractionIntoWhole
Message: 0.3 has a fraction, and speed holds whole numbers from 0 to 255.
Decimal Literals explains this message.
wrongType
Message: paused: This is a number from 0 to 255, but a yes-or-no value is needed here.
Types explains this message.
arraySize
Message: A list needs between 1 and 65,535 places.
Lists explains this message.
emptyArray
Message: An empty list doesn't say what it would hold.
List Values explains this message.
textForOnePlace
Message: A single place on the screen holds one character, not a text of 1 character.
Characters and Screen Codes explains this message.
hardwareArithmetic
Message: Color has no addition.
Named Sets explains this message.
hardwareConversion
Message: A Note cannot convert directly to Color.
Named Sets explains this message.
memberNeedsType
Message: Nothing here gives .blue a type.
Named Sets explains this message.
nextNeedsGroup
Message: next moves on to the next name in a group of names.
Named Sets explains this message.
Structs and Enums
These messages guide you when declaring custom struct and enum types, building their values, and matching on their cases and fields.
wireHeader
Message: A wire names its size in bytes, as in wire Header(bytes: 3).
Wire Records explains this message.
wireLayout
Message: This wire's layout can't be used.
Wire Records explains this message.
structName
Message: A struct's name starts with a capital letter, and speed does not.
Structs explains this message.
aliasName
Message: A type's name starts with a capital letter, and screen does not.
Type Aliases explains this message.
structFieldNeedsType
Message: The field x of Speed doesn't say what kind of value it holds.
Structs explains this message.
structFieldRepeated
Message: Speed has two fields called x.
Structs explains this message.
structSizeConstant
Message: size must be a constant because Buffer's memory is fixed when the program is built.
Type Parameters explains this message.
structBody
Message: An Item body holds fields and functions.
Struct Blocks explains this message.
structDefaultConstant
Message: The default for value must be a constant.
Struct Blocks explains this message.
structFieldScope
Message: x is already a field of Item.
Struct Blocks explains this message.
structMakerOwner
Message: A maker inside Item belongs to Item, not Other.
Struct Blocks explains this message.
structMutationUndeclared
Message: add_one changes its Score but is declared with fn.
Struct Blocks explains this message.
structMutationMethodOnly
Message: read cannot be declared with mut fn.
Struct Blocks explains this message.
structChangingPlace
Message: bump is declared mut fn and needs an Item place that can change.
Struct Blocks explains this message.
structPresence
Message: xs[0] may hold no value.
Struct Blocks explains this message.
structAction
Message: ping gives no value.
Struct Blocks explains this message.
structNeedsContext
Message: (a: 1) doesn't say which struct it is.
Structs explains this message.
structPositional
Message: (1, -2) gives values without saying which field each one fills.
Structs explains this message.
duplicateField
Message: The field x appears twice in this struct.
Structs explains this message.
unknownField
Message: z isn't a field of a sprite.
Structs explains this message.
enumName
Message: An enum's name starts with a capital letter, and mode does not.
Enums explains this message.
enumNoCases
Message: The enum Mode has no cases.
Enums explains this message.
enumValue
Message: The values of Ink need another form.
Enums explains this message.
enumEnumeration
Message: Drag has cases with fields, so it cannot be enumerated.
Enums explains this message.
enumCaseRepeated
Message: Mode has two cases called a.
Enums explains this message.
enumCaseName
Message: A case of Mode starts with a lowercase letter, and A does not.
Enums explains this message.
noCase
Message: Mode has no case called c.
Enums explains this message.
notAMember
Message: playng is not one of the members of this enum.
Enums explains this message.
caseNeedsFields
Message: The case a of Choice carries p, so a value of it gives them.
Enums explains this message.
caseHasNoFields
Message: The case b of Choice carries no fields.
Enums explains this message.
caseFieldRepeated
Message: The field p of a is given twice.
Enums explains this message.
casePositional
Message: 1 gives a value without saying which field it fills.
Enums explains this message.
enumCompare
Message: e == .a(p: 1) compares a value of Choice, and == compares only with a case that carries no fields.
Enums explains this message.
enumFieldRead
Message: A value of Choice carries p in some of its cases only, so a dot cannot read it.
Enums explains this message.
casePatternFields
Message: The case b carries no fields, so its line names none.
Patterns explains this message.
armFieldRepeated
Message: This line takes the field p twice.
Patterns explains this message.
positionCaseAmbiguous
Message: More than one enum has a case called east: Path and Compass.
Bit Operations explains this message.
positionCaseUnknown
Message: No enum has a case called eats.
Bit Operations explains this message.
bitwisePositionCases
Message: Wide has 9 cases, but this number has only 8 bits.
Bit Operations explains this message.
Expressions and Conversions
These messages help you with arithmetic operators, explicit conversions, list indexing and slicing, value if and match expressions, function calls, and built-in members.
cannotCombine
Message: shade and 2 can't be used with ==.
Comparisons explains this message.
needsNumbers
Message: + works on numbers, but this is a Mode.
Arithmetic explains this message.
negationNeedsNumber
Message: A minus sign in front works on numbers, but this is a ScreenCode.
Arithmetic explains this message.
operationNeedsRange
Message: +% needs a declared range to wrap in.
Wrapping and Clamping explains this message.
rangeExceeded
Message: speed takes values from 0 to 9, but this one can reach 15.
Checked Arithmetic explains this message.
divisionByZero
Message: This divides by zero.
Division and Remainder explains this message.
needsBooleans
Message: and joins two yes-or-no values.
and, or and not explains this message.
notNeedsBool
Message: not turns yes into no, but this is a number from 0 to 255.
and, or and not explains this message.
optionalCompare
Message: a and b can't be compared.
Comparisons explains this message.
coalesceNeedsOptional
Message: ?? supplies a stand-in for a value that might be missing, but this is a number from 0 to 255, which is never missing.
Optionals and ?? explains this message.
conversionNeedsNumber
Message: Only numbers can be converted to Number<u8>.
Number Conversions explains this message.
conversionOutOfRange
Message: 300 is outside a Number<u8>, which holds 0 to 255.
Number Conversions explains this message.
conversionDropsFraction
Message: speed has a fraction, and a Number<u8> holds only whole numbers.
Number Conversions explains this message.
digitsNeedsWhole
Message: 0.5 holds a fraction, and digits writes only whole numbers.
Other Number Functions explains this message.
sqrtInput
Message: sqrt needs a whole number from 0 to 65,535.
Other Number Functions explains this message.
bitwiseReceiver
Message: bitwise_and needs a number with a chosen unsigned width.
Bit Operations explains this message.
bitwiseArgument
Message: This position is 8, but bit_is_set allows 0 through 7.
Bit Operations explains this message.
indexNeedsArray
Message: Square brackets pick one place out of a list, but this is a number from 0 to 255.
Indexes explains this message.
indexNotInteger
Message: A place in a list is chosen with a whole number, but this is a number from 0.0 to 255.996.
Indexes explains this message.
indexOutOfBounds
Message: Place 4 doesn't exist in a list of 4.
Indexes explains this message.
arrayShapes
Message: These two lists have different sizes: [2 of Number<u8>] and [3 of Number<u8>].
Lifted Operations explains this message.
argumentShapes
Message: These lists have different sizes.
Lifted Operations explains this message.
sliceLengthUnknown
Message: The length of left..<width isn't known when the program is built.
Windows explains this message.
sliceStartEffect
Message: The slice advance(mut pos)..<(advance(mut pos) + 4) can't use advance(mut pos), which changes something each time it runs.
Windows explains this message.
sliceOutOfBounds
Message: This range goes past the end of a list of 40.
Windows explains this message.
sliceStartOutside
Message: A slice of 4 places can't start at a, which is 6 to 7.
Windows explains this message.
sliceOfColumn
Message: A slice can't start at a changing place in shots.x, which is the x of every place in shots.
Windows explains this message.
sliceBindingWrite
Message: strip names part of xs, which can't change, so its places can't be written.
Windows explains this message.
sliceBindingType
Message: field names [2 of Number<u8>], but its annotation says [3 of Number<u8>].
A named window's annotation must match the backing places exactly. Use the same shape and element type, omit the annotation, or initialize a var to keep a separate value.
rectangleRanges
Message: A rectangle takes two ranges, rows and then columns, but 1 is not a range.
Rectangles explains this message.
rectangleRows
Message: A rectangle picks rows and columns, but this is [8 of Number<u8>], and its places are not rows.
Rectangles explains this message.
rectangleBase
Message: A rectangle is cut from a list that has a name, and pick(xs) is a calculation.
Rectangles explains this message.
rectangleShape
Message: This rectangle is 2 rows of 3, but the place for it is 3 rows of 3.
Rectangles explains this message.
rectangleWrite
Message: xs[0..<2, 0..<3] is a rectangle, and a binding with <- has no handler to set it row by row.
Rectangles explains this message.
joinLists
Message: ++ joins two lists of the same kind of thing, and this joins [2 of Number<u8>] to Number<u8>.
Joining Lists explains this message.
collectionArrow
Message: This collection arrow cannot be used here.
map and filter explains this message.
reductionInput
Message: any needs a list of yes-or-no values.
Reductions explains this message.
sumNeedsNumber
Message: sum adds up numbers, so its result must be a number type.
Reductions explains this message.
listChangeContext
Message: add changes a list, so call it in a when handler or a function that keeps the list.
Calls and Device Actions explains this message.
valueIfElse
Message: An if that gives a value needs an else.
if explains this message.
conditionalMatch
Message: This conditional match needs when lines and a final else -> line.
match Without a Value explains this message.
missingCoverage
Message: This match doesn't say what to do for every possible value.
match on a Value explains this message.
duplicateArm
Message: 1 is already handled by an earlier line of this match.
match on a Value explains this message.
invalidPattern
Message: A line of a match starts with nil, a number, a quoted character, or a name.
match on a Value explains this message.
characterPattern
Message: A quoted pattern is one character, but this one is "ab".
match on a Value explains this message.
nilArm
Message: nil is an answer only for a value that might be missing.
match on a Value explains this message.
badArgument
Message: apart doesn't take an input called c, or it was given twice.
Calls explains this message.
missingArgument
Message: digits needs count, and it was left out.
Calls explains this message.
argumentRange
Message: a holds 24 to 320, but short_value is 3.
Calls explains this message.
argumentListSize
Message: xs takes a list of 4, but this list holds 3.
Calls explains this message.
noMember
Message: A number from 0 to 255 has nothing called foo.
Members explains this message.
memberValue
Message: This member is stored; read it without parentheses.
Members explains this message.
randomNeedsRange
Message: random picks from a range of numbers written out.
Random Numbers explains this message.
mustBeFixedWhole
Message: The history length must be a whole number from 1 to 65,535, written out.
Reductions explains this message.
Events, Handlers and Waiting
These messages guide you when working with events, when handlers, wait timelines, forever loops, top-level cases, and queues.
whenSubject
Message: shot is a stored optional, so when has no frame to filter.
Handlers explains this message.
onNeedsEvent
Message: This doesn't name an event; it is a yes-or-no value.
on: and reset: explains this message.
notEvent
Message: not turns yes into no, but an event is not a yes-or-no value.
Events and Conditions explains this message.
andEvents
Message: An event cannot be joined to another event with and.
Events and Conditions explains this message.
orNeedsEvents
Message: or joins two events, or two yes-or-no values, but not one of each.
Joined Events explains this message.
andOnLine
Message: A when line filters its event with when, not and.
Filters explains this message.
eventNoValue
Message: lives.changed carries no value, so there is nothing to give v.
Events That Carry a Value explains this message.
timeNeedsRange
Message: The count member needs a binding with its own range.
Ranges and Periods explains this message.
countWillOverflow
Message: This count will run out of range after 4 counted firings.
The event keeps firing and nothing restarts the count. Use .cycle() to wrap, or .countdown(from:) to count down and stay at the bottom. Ranges and Periods explains these choices.
timePeriod
Message: The every member needs a whole period in range.
Ranges and Periods explains this message.
timePayload
Message: The latest member needs an event that carries a value.
Events That Carry a Value explains this message.
sampledPayload
Message: Sampling cannot retain Pool of (2 of Number<u8>).
Sampling a value explains the ordinary values sampling can retain.
guardOutsideHandler
Message: guard needs a handler or a value function or op.
Guard explains this message.
guardNeedsFallback
Message: This value guard needs else value.
Write guard condition else value to return a fallback when a function or op's test fails.
waitOutsideHandler
Message: wait belongs in a when handler.
Wait explains this message.
waitNeedsEventOrFrames
Message: wait takes an event or a number of frames, and true is a yes-or-no value.
Wait explains this message.
waitNoFrames
Message: wait(0) would not pause.
Waiting for Frames explains this message.
waitMayNotPause
Message: wait(delay) would not pause when delay is 0.
Waiting for Frames explains this message.
waitTimeUnit
Message: wait(minutes: 2) has to count time in seconds: or ms:, one of them.
Waiting for a Time explains this message.
waitTimeAmount
Message: wait(seconds: 0) needs a fixed number above zero.
Waiting for a Time explains this message.
waitTimeLong
Message: wait(seconds: 3000) is 182978 frames on an early NTSC machine, more than a wait can count.
Waiting for a Time explains this message.
waitEventReadsLocal
Message: wait System.keyboard[s.key].released reads s, which this handler gave its value.
Waiting for an Event explains this message.
waitOnTimerLoop
Message: tick fires once, 500 milliseconds after the program starts, so this wait would never end on the loop's second turn.
Waiting for a Timer explains this message.
waitOnTimerElsewhere
Message: tick fires once, 2 seconds after the program starts, so a wait for it can only work in a when start of the program or case that declares it.
Waiting for a Timer explains this message.
waitOnTimerLate
Message: tick fires once, 500 milliseconds after the program starts, and this wait can begin after that, so it would never end.
Waiting for a Timer explains this message.
waitOnTimerTwice
Message: tick fires once, and the wait on line 3 already uses it.
Waiting for a Timer explains this message.
foreverNeverWaits
Message: This forever can go round again without a wait.
Forever explains this message.
breakInForever
Message: break cannot leave a forever.
Forever explains this message.
caseDeclaration
Message: A type can't be declared inside a match.
What a Case Holds explains this message.
outputMatch
Message: An output's lines can't hold a match of declarations.
Cases explains this message.
caseStartLong
Message: Starting the case true needs 36,211 cycles in one frame, and a PAL frame holds 19,656.
Changing Cases explains this message.
queueForm
Message: This queue cannot be used this way.
Queues explains this message.
queueConsumer
Message: The queue q already has a take.
Queues explains this message.
Statements and Loops
These messages help you with assignments, if statements, unwrapping optionals in conditions, and for loops.
notAssignable
Message: limit is a constant, so it can't be given a new value.
Places That Cannot Be Assigned explains this message.
assignUndeclared
Message: scor isn't declared, and a statement in a when handler can't introduce a name.
Places That Cannot Be Assigned explains this message.
wrongLength
Message: This list holds 3 things, but 2 places are being filled.
Elements, Fields and Windows explains this message.
conditionNeedsBool
Message: A condition must be a yes-or-no value, but this is a number from 0 to 255.
If Statements explains this message.
bareOptional
Message: shot may be missing, and a condition needs a yes or no.
Conditional Names explains this message.
assignExisting
Message: done is already a name, so = here would not compare. Did you mean ==?
Conditional Names explains this message.
alwaysSucceeds
Message: if gap = n + 1 always succeeds, so the body would always run.
Conditional Names explains this message.
assignedAgain
Message: s was assigned in a condition, so it can't be given a new value.
Conditional Names explains this message.
secondAssignment
Message: An if condition assigns one name, and writes it first.
Conditional Names explains this message.
orAfterAssignment
Message: n would not be assigned when only the other side of or happens.
Conditional Names explains this message.
whenInCondition
Message: if tests with and, not when.
If Statements explains this message.
loopAtTopLevel
Message: A for goes inside a when handler or a function, not at the top of the program.
For Loops explains this message.
forNeedsList
Message: A for goes through a list or a range, and x is a number from 0 to 9.
For Loops explains this message.
forRangeNeedsWhole
Message: A for counts whole numbers, and 0.5...3 is not one.
Over a Range explains this message.
loopVariableSet
Message: i is the loop's value for this turn, so it can't be given a new value.
The Loop's Name explains this message.
loopListChanged
Message: This loop goes through xs, so a line inside it cannot change xs.
Over a List explains this message.
breakOutsideLoop
Message: break has no loop to leave here.
Break explains this message.
loopOverrun
Message: This loop can't finish within one PAL frame.
Loops and the Frame explains this message.
Devices
These messages help you navigate the Commodore 64 hardware under System: device paths, the screen, text regions, pixel canvases, sprites, the keyboard, sound voices, and the clock.
systemAlone
Message: System is the machine itself, not a value.
Paths explains this message.
noDevice
Message: System has no device called banana.
Paths explains this message.
noPart
Message: System.joystick[2] has no dz.
Paths explains this message.
noInstance
Message: System.joystick[3] is not a joystick the machine has.
Devices With Numbers explains this message.
instanceNeeded
Message: The machine has more than one joystick, so System.joystick needs the number of the one you mean.
Devices With Numbers explains this message.
instanceRange
Message: port picks the joystick, but it is 3.
Devices With Numbers explains this message.
chosenDevice
Message: System.joystick[p] is the joystick that a number picks while the program runs, so it is not a device a name can stand for.
Naming a Device explains this message.
deviceNotValue
Message: System.keyboard is a device, and only a constant holds one.
Naming a Device explains this message.
deviceNamed
Message: System.screen is named screen; write screen.border.
Naming a Device explains this message.
deviceHasNoPlaces
Message: System.screen is a device, and a device has parts, not places.
Paths explains this message.
notBuilt
Message: System.georam is not built yet.
Devices Not Built Yet explains this message.
registerAssigned
Message: reg is a register, so a statement can't give it a value.
Hardware Registers explains this message.
hardwareBound
Message: reg has a binding, so it can't also be set by hand.
Hardware Registers explains this message.
hardwareInvalid
Message: This memory address and its type don't fit.
Hardware Registers explains this message.
rasterSelection
Message: The rows picked here must be written out and be between -51 and 210.
Color Bands explains this message.
rasterLine
Message: Row 219 exists only on PAL; the last row every standard has is 210.
Color Bands explains this message.
textScreenOutput
Message: This is a screen output. Print into a region of the screen, or bind a value to it with <-. For color: This is a screen output. A handler cannot assign it; bind a color to it with <-, as in System.screen.color[row] <- .yellow.
Text and Ink explains this message.
textLayout
Message: This Text placement can't be used: a height needs .width(...) too.
Text Placement explains this message.
For a text with .cursor(...), show System.keyboard.line (or a pure alias) directly through System.screen.content. Set keyboard.line.capacity, use a constant screen position and a machine font, and use .wrapped(.character) in a wrapped box. Remove .aligned(...) from the editing view; previews without a cursor can keep it. Multi-row views with a cursor must all have the same width and height. Showing the input cursor lists the supported shapes.
multicolorInk
Message: Multicolor text (line 1) keeps its ink to the first eight colors, Color.black through Color.yellow.
Multicolor Text explains this message.
multicolorScene
Message: System.screen.multicolor needs one binding for the whole text screen.
Multicolor Text explains this message.
multicolorNeedsMode
Message: .multicolor(color) needs multicolor text.
Multicolor Text explains this message.
multicolorBeside
Message: Text next to multicolor text (line 1) cannot use colors from Color.orange on yet.
Multicolor Text explains this message.
rectangleBinding
Message: A part of the screen is a region.
Regions and Printing explains this message.
regionArgument
Message: A region has no rows.
Regions and Printing explains this message.
regionConstant
Message: A region's row is a whole number written out.
Regions and Printing explains this message.
regionOutside
Message: This region does not fit inside the screen.
Regions and Printing explains this message.
regionOverlap
The message names both regions: the second one uses cells that the first one already holds.
Regions and Printing explains this message.
regionPlace
Message: A region is declared on a line of its own.
Regions and Printing explains this message.
regionCall
Message: Region is not a name a program can call.
Regions and Printing explains this message.
regionValue
Message: log is a part of the screen, not a value.
Regions and Printing explains this message.
regionInFunction
Message: A function or work cannot use log.print.
Regions and Printing explains this message.
regionMove
Message: move takes a row and a column.
Region Members explains this message.
regionText
Message: This text does not fit inside log.
Region Members explains this message.
pageShape
Message: This grid has 4 rows of 2 cells, but this region has 3 rows of 2 cells.
Region Members explains this message.
printList
Message: print needs a list of characters.
Printing explains this message.
printElements
Message: print accepts lists of Char or ScreenCode; this list holds Color.
Printing explains this message.
printControl
Message: This text contains a control character at position 1.
Printing explains this message.
printExpression
Message: print changes a region and returns no value.
Printing explains this message.
pageOutruns
Message: log can scroll faster than the screen can show it.
Printing explains this message.
canvasArgument
Message: canvas cannot take colour: this way.
Canvases explains this message.
canvasLeaves
Message: A canvas of 40 by 8 cells at row 20, column 0 does not fit the screen.
Canvases explains this message.
canvasMore
Message: other is a second canvas, and the screen shows one canvas at a time.
Canvases explains this message.
canvasAlone
Message: picture is a canvas, and a canvas is a part of the screen, not a value.
Canvases explains this message.
canvasText
Message: This text update next to a canvas (line 1) is not built yet.
Canvases explains this message.
modePart
Message: System.screen.text belongs to text, and this case shows a canvas (line 4).
Canvases explains this message.
bitmapText
Message: System.screen.text belongs to text, and this program shows a canvas (line 1).
Canvases explains this message.
bitmapBackground
Message: A hires canvas has no System.screen.background; use its background.
Canvases explains this message.
multicolorCanvas
Message: picture is a canvas, and the multicolor text of line 1 is already on the screen.
Canvases explains this message.
bitmapList
Message: A canvas shows a list of drawings.
Drawings explains this message.
pixelInput
Message: These pixels need another form.
Canvas pixels explains this message.
pixelColors
Message: Ink has 4 colors, but a multicolor canvas allows the background plus 3.
Canvas pixels explains this message.
drawingElement
Message: A drawing is picture.place(...), picture.fill(...), line(from:, to:), points.lines(), circle(x:, y:, radius:), corners.outline(), nil, or an if or match that chooses between them.
Drawings explains this message.
placeOutside
Message: place makes a drawing, and drawings go in the list bound to a canvas's drawings.
Drawings explains this message.
outlineOutside
Message: outline makes a drawing, and drawings go in the list bound to a canvas's drawings.
Drawings explains this message.
outlineInput
Message: This outline has an input it cannot use.
Drawings explains this message.
regionFontLayout
Message: This combination of region fonts and screen updates is not built yet.
Regions and Printing explains region fonts. The compiler must keep all their visible glyphs and screen updates together; some changing fonts or screen combinations still need another complete-picture path.
placeInput
Message: This place has an input it cannot use.
Drawings explains this message.
fillRange
Message: width must be at least 1, and here it is 0.
Drawings explains this message.
lettersInput
Message: This lettering has an input it cannot use.
Drawings explains this message.
lettersMode
Message: A hires font cannot letter a multicolor canvas.
Drawings explains this message.
bitmapMixed
Message: One place of a canvas's drawings list holds a picture or an outline, not both.
Drawings explains this message.
drawingFnOutside
Message: two returns drawings, and drawings go in the list bound to a canvas's drawings.
Drawings explains this message.
drawingFnBody
Message: two returns drawings, and its body is not a list of them.
Drawings explains this message.
drawingFnCount
Message: two says it returns 2 drawings, and its list has 1.
Drawings explains this message.
placeRange
Message: x must stay within 0...312 for this picture, and here it is 320.
Where a Drawing May Go explains this message.
placeShifted
Message: A fill that starts or ends between whole bytes has its width written out.
Where a Drawing May Go explains this message.
placeColoredShifted
Message: A picture with its own colors sits on whole cells, so x is a multiple of 8.
Where a Drawing May Go explains this message.
placeOdd
Message: In a multicolor canvas a pixel is two wide, so x has to be even.
Where a Drawing May Go explains this message.
placeCells
Message: A picture with its own colors sits on whole cells, so y is a multiple of 8.
Where a Drawing May Go explains this message.
placeColors
Message: A picture with its own colors needs a canvas color and background that stay the same.
Where a Drawing May Go explains this message.
spriteIndex
Message: The sprite number must be written out, from 0 to 7.
Sprites as a List explains this message.
spriteNeedsStruct
Message: A sprite is set with a struct that gives its x and y.
Sprites explains this message.
spriteFieldRequired
Message: This sprite has no x.
Sprites explains this message.
spriteFieldRange
Message: The sprite's x can reach 600, but it must stay within -24...487.
Sprites explains this message.
spriteBoundTwice
Message: Sprite 0 is set on line 1 and again on line 2.
Sprites explains this message.
spriteNotReadable
Message: System.screen.sprite can't be read: the sprites are only set, never read back.
Sprites explains this message.
spriteListLength
Message: System.screen.sprite[0..<4] has 4 places, but the list has 3 sprites.
Sprites as a List explains this message.
spriteListNeedsSprites
Message: A list of sprites is set with a list of Sprite values, or of values that may be missing.
Sprites as a List explains this message.
keyLiteral
Message: System.keyboard[.space] names a key that is known when the program is written, so the key is a part of the device.
Keys explains this message.
keyChoice
Message: A key is chosen with one Key value, but this is [3 of Key].
Keys explains this message.
keyboardLineCapacity
Message: The keyboard line needs a capacity.
The Typed Line explains this message.
controlPortOne
Message: System.joystick[1].fire and System.paddle[1] (line 1) are both on control port 1.
Control Port 1 explains this message.
toneEnvelopeConflict
Message: Give tone a decay or an envelope, not both.
Tone explains this message.
tonePitchConflict
Message: Specify pitch as a note, an explicit frequency, or hz, not a combination of them.
Tone explains this message.
tonePitchMissing
Message: Tone requires a note, a frequency, or hz to specify its pitch.
Tone explains this message.
noteWrap
Message: Notes do not wrap; a tune cycles its index.
Tone explains this message.
playVoice
Message: voice is 1, 2 or 3, written out, and v is not.
Play and Release explains this message.
playOutsideOn
Message: play can only be used inside a when handler.
Play and Release explains this message.
playIsAction
Message: play makes a sound; it does not give back a value.
Play and Release explains this message.
voiceBindingIndex
Message: A voice that holds a value is 1, 2 or 3, written out, and v is not.
Binding a Voice explains this message.
voiceBoundTwice
Message: Voice 1 is set by two lines at the same level, on lines 1 and 2.
Binding a Voice explains this message.
voiceBoundAndCalled
Message: Voice 1 is bound on line 2 and also takes play on line 4.
Play and Release explains this message.
voiceCalledAround
Message: Voice 1 takes play on line 3, outside the case that binds it on line 7.
Binding a Voice explains this message.
periodicPeriod
Message: A clock period needs a positive constant duration.
Intervals and Timers explains this message.
periodicOwnership
Message: This program cannot keep the clock source's timing guarantee.
Intervals and Timers explains this message.
Costs and the Frame
These messages help you keep your program inside the Commodore 64's frame budget and memory map—checking frame timing, fast choices, background work jobs, and available RAM.
frameOverrun
Message: The work in one PAL frame, with the screen's share of the processor and the runtime's own steps, can take up to 21,618 cycles, and the frame holds 19,656.
A Frame Too Long explains this message.
frameUnbounded
Message: The compiler can't tell how long the asm block on line 3 takes, so it can't check that the frame fits.
Work Without a Limit explains this message.
frameUnproved
Message: The compiler can't count how long the frame's work takes at line 10, so it can't check that the frame fits.
When the work is a write to the text or the colors the screen is showing, the message names the write and says that the compiler can't prove the write lands after the screen has drawn what it changes. A program that uses the disk drive and also writes the screen this way gets a message that names the line of the drive call and the line of the write. Text or colors the program would show in place from its own list are copied instead, so they don't reach this message. The program is refused rather than run unchecked. This is a gap in the compiler, not a mistake in your program; please report it with the program. Work Without a Limit explains this message.
frameDeadline
Message: .deadline(line:) needs a fixed whole picture row in -51...204 on PAL, NTSC and early NTSC.
Use a constant line in .deadline(line:) at the end of a direct frame or native raster trigger in a when header. The compiler must also prove that the complete work finishes before that line. If a valid line still cannot be proved, shorten the update, check values before the first visible write, or choose a later line that meets your application's needs. Completing Before a Picture Row shows complete examples and the timing contract.
segmentOverrun
Message: when start has a stretch of code, the code after the wait on line 9, that can't finish within one PAL frame.
A Stretch Between Waits explains this message.
printBudget
Message: This print cannot finish in one frame on early NTSC.
Work Divided Between Frames explains this message.
fastHead
Message: fast can't mark a var declaration.
Where fast Cannot Go explains this message.
codeMarkConflict
Message: fast and small both mark this line.
Keep one mark on a head. A composed row also cannot serve regions marked both fast and small; the message names both source lines.
Where fast Cannot Go explains this message.
fastRepeated
Message: fast is written twice on this head.
Where fast Cannot Go explains this message.
fastAsm
Message: fast can't mark an asm block.
Where fast Cannot Go explains this message.
workProgressMissing
Message: answer.progress has no progress values to show.
Put publish value inside the work loop, using the same type as the final answer. Changing a local or returning the answer does not offer progress. Work Progress shows a complete example.
workPublication
Message: Use publish value only inside a work body.
Use publish expression inside work to offer a complete value of its return type. Progress must be a fixed ordinary value; resources, events, job handles and mutable collections cannot be offered as progress. A job's progress and running members are read-only. Work Progress explains their frame snapshots.
publication
Message: The current value of displayed is read-only. Copy it into a var before changing it.
Declare a program-level const name = Publication(initial: value), share one ordinary value with name.publish(value) in foreground code, and read name.current as an immutable value. Resources, events, jobs, callbacks and mutable collection services cannot be payloads. Publications shows complete examples.
jobForm
Message: This work can't run in that form: give within one count, as in within(frames: 40).
Work explains this message.
jobUnbounded
Message: The work has no proven bound.
Parts of a Job explains this message.
jobPartTooLong
Message: Running the loop on line 4 to its end needs 19,697 cycles on PAL, more than a frame.
Parts of a Job explains this message.
jobFrameFull
Message: The frame needs 134,382 cycles on early NTSC with resume() in it, and a frame has 16,768.
Parts of a Job explains this message.
jobStepDeadline
Message: A job that a handler steps cannot take a deadline.
Parts of a Job explains this message.
jobDeadline
Message: This job deadline is not proven.
Parts of a Job explains this message.
outOfMemory
Message: This program needs more memory than the Commodore 64 has free.
When the Compiler Spends Bytes Itself explains this message.
bitmapSecondImage
Message: Keeping the old bitmap needs another 9,024 bytes for a whole picture, colors and sprite shapes; the largest usable screen storage area has 6,153 bytes left.
When the Compiler Spends Bytes Itself explains this message.
bitmapImageEnd
Message: This bitmap program is 160 bytes too large: its code and data must fit in 50,175 bytes.
When the Compiler Spends Bytes Itself explains this message.
Assembly and Placement
These messages help you write safe 6510 asm blocks, assembly functions, hand-written bindings, interrupt routines, and memory-mapped at declarations.
topLevelAssembly
Message: Assembly can't sit at the top of a program, outside a when handler.
Assembly Blocks explains this message.
assemblyCli
Message: cli can only appear in a when start block.
Registers and Flags explains this message.
unknownInstruction
Message: foo isn't a 6502 instruction Adder can assemble.
Instructions explains this message.
badInstructionForm
Message: lda can't be written that way.
Instructions explains this message.
assemblyForm
Message: stx can't be written that way on the original 6502.
Instructions explains this message.
assemblyUnstable
Message: lax # can't be used: LXA ($AB) is an unstable opcode.
Instructions explains this message.
assemblyJam
Message: jam can't be used: the JAM opcodes ($02, $12, $22, $32, $42, $52, $62, $72, $92, $B2, $D2 and $F2) stop the processor.
Instructions explains this message.
operandSize
Message: The value 300 doesn't fit in 1 byte.
Operands explains this message.
branchTooFar
Message: A branch has to go 130 bytes, which is further than the 6502 can reach in one step (127 forward or 128 back).
Labels explains this message.
assemblyLabelCollides
Message: The assembly label short_value is already the name of something in the program.
Labels explains this message.
assemblyLabelSelector
Message: An assembly label doesn't have a low or high byte of its own.
Labels explains this message.
assemblyUnknownName
Message: later isn't a name the assembly can see.
Names in Assembly explains this message.
A label of a case's when start is seen only in that case, so naming it from another case gets the message with two more lines. They say that it is a label in the when start on a given line, and that only the blocks in that case can name it, and they advise labeling a cell in a when start outside the match to share it between cases.
assemblyNeedsScalar
Message: a holds more than one number, so assembly can't use it as one value.
Values With an Address explains this message.
assemblyTooWide
Message: t takes 3 bytes, more than assembly can read as one value.
Values With an Address explains this message.
assemblyWide
Message: pos is two bytes wide, so assembly has to say which byte it wants.
Values With an Address explains this message.
assemblyNarrow
Message: short_value is one byte wide, so it has no high byte.
Values With an Address explains this message.
assemblyByteOffset
Message: A byte offset on seed needs a list of bytes and an offset within it.
Values With an Address explains this message.
assemblyNoAddress
Message: spot doesn't live in memory, so assembly has no address for it.
Constants explains this message.
assemblyConstantWrite
Message: table is a constant, so assembly cannot write it.
Constants explains this message.
assemblyInputWrite
Message: System.screen.frames is a sampled input and cannot be written.
Devices explains this message.
assemblyScratch
Message: scratch is four bytes, so it takes an offset from 0 to 3 and no .lo or .hi.
Scratch explains this message.
assemblyWritesName
Message: writes(missing) must name a variable or a binding.
The writes Clause explains this message.
cyclesNeeded
Message: cycles needs a whole number, and found x.
The cycles Clause explains this message.
cyclesRange
Message: cycles(30...20) is not a range of cycles.
The cycles Clause explains this message.
cyclesStandard
Message: cycles has figures for pal, ntsc and early_ntsc, and found secam.
The cycles Clause explains this message.
cyclesOneStandard
Message: cycles gives a figure for pal and none for ntsc.
The cycles Clause explains this message.
cyclesRepeated
Message: cycles gives pal two figures.
The cycles Clause explains this message.
mutableAssemblyProof
Message: Adder can't prove this changing assembly body.
Use named fields or mut parameters for writes, and keep list indices within their bounds. Use a counted loop with a fixed or bounded input when Adder can count it, or give the body a cycles(...) allowance. An allowance supplies timing and every indexed access still needs a proof. Changing fields and parameters explains the checks.
assemblyParameterWrite
Message: n is a parameter, so assembly can't change it.
Assembly Functions explains this message.
assemblyRegisterParameter
Message: a can't name a parameter of a function written in assembly.
Assembly Functions explains this message.
assemblyResultUnwritten
Message: result is not written on every path through this assembly.
Assembly Functions explains this message.
assemblyImpure
Message: A function's assembly cannot use System.screen.border this way.
Assembly Functions explains this message. A store through a pointer gets the message: A function's assembly cannot store through a pointer: sta (scratch),y.
handImpure
Message: A hand-written block cannot use System.screen.border this way.
Hand-Written Bindings explains this message. A store through a pointer gets the message: A hand-written block cannot store through a pointer: sta (scratch),y.
handWrittenMemory
Message: System.joystick[2].dx.sum(from: 0) keeps memory between frames, so a block cannot stand in for it.
Hand-Written Bindings explains this message.
handWrittenRead
Message: The block reads b, which a never mentions.
Hand-Written Bindings explains this message.
handWrittenTarget
Message: A hand-written block can only write a destination that sits in memory at a fixed address.
Hand-Written Bindings explains this message.
assemblyInterruptWrite
Message: Interrupt code writes hits, which belongs to the program.
What a Routine May Touch explains this message. A store through a pointer gets the message: An interrupt routine cannot store through a pointer: sta ($90),y.
assemblyInterruptScratch
Message: Interrupt code cannot use scratch.
What a Routine May Touch explains this message.
rasterOwner
Message: The routine on line 2 chooses its own raster lines, so it cannot share the raster interrupt with a binding that shows System.screen.border or System.screen.background by raster line.
Routines That Pick Their Own Lines explains this message.
interruptInstall
Message: The asm block on line 4 sets up an interrupt by storing to $0314, so the compiler can't tell when it runs or check that the frame fits.
Installing by Hand explains this message.
interruptRoutineForm
Message: The handler on line 1 is marked fast, and an interrupt routine takes no mark.
Interrupt Routines explains this message.
interruptWrite
An interrupt passed an outer variable, field or element as a mut argument. Pass an invocation-local place; change shared state in a foreground handler.
interruptUnsafe
An interrupt attempted an outer write, suspension, unsupported service/helper call, uncontrolled mixed-body nesting or an unbounded stack use. The message names the interrupt and operation; unsafe value calls include their call path. Use invocation locals, bounded value calculations and immediate scalar chip-register stores. Shared mutation and services belong in foreground handlers.
Interrupt Routines describes the supported forms and write rules.
interruptLine
Message: System.screen.interrupt takes line: and a whole picture row from -51 to 210, and found 249.
Interrupt Routines explains this message.
interruptPeriod
Message: The period of System.clock.interrupt can be at most 64 milliseconds, and this one is longer.
Routines on a Timer explains this message.
interruptRuns
Message: runs(...) belongs to the asm block of an interrupt routine.
Routines That Pick Their Own Lines explains this message.
interruptOverrun
Message: The routine at picture row 58 takes so long on PAL that the interrupt for picture row 70 comes too late to be set up.
Routines That Pick Their Own Lines explains this message.
interruptTimer
Message: The timer routine on line 6 and the one on line 1 would both need the program's timer.
Routines on a Timer explains this message.
interruptSlow
Message: The routine on line 1 can take 1,526 cycles on PAL, and its timer fires every 986.
Routines on a Timer explains this message.
assemblyZeroPage
Message: An asm block cannot use $10, which is in the zero page the compiler hands out.
Memory a Block May Not Use explains this message.
bitmapAssembly
Message: An asm block in a bitmap program cannot write $DD00.
Memory a Block May Not Use explains this message.
romAssembly
Message: An asm block in a program that changes screen mode can't use $FFD2.
Memory a Block May Not Use explains this message.
listOffBoundary
Message: tiles is placed at 49,408, but a screen the chip shows must start on a 1,024-byte boundary.
Placing a Value in Memory explains this message.
listInCharacterImage
Message: screen is placed at 4,096, where the chip sees the character set and not memory.
Placing a Value in Memory explains this message.
placedOnPort
Message: t is placed on the processor's own port, the first two bytes of memory.
Placing a Value in Memory explains this message.
placedOverProgram
Message: t is placed from 2,049 to 2,112, over the program itself.
Placing a Value in Memory explains this message.
placedVicOwned
Message: chosen is placed over $D018, which the screen already sets from line 3.
Placing a Value in Memory explains this message.
placedVicSplit
Message: pair is placed over video chip registers of two kinds.
Placing a Value in Memory explains this message.
placedOverRuntime
Message: t is placed from 16 to 79, over the zero page the program keeps its values in.
Placing a Value in Memory explains this message.
placedOverPicture
Message: t is placed from 57,600 to 57,663, over the picture the program draws.
Placing a Value in Memory explains this message.
placedOverScreen
Message: tiles is placed from 1,280 to 1,283, over the screen the program shows.
Placed Values explains this message.
placedOverList
Message: b is placed from 49,153 to 49,216, where a already lies.
Placing a Value in Memory explains this message.
ownedScreenShared
Message: Line 3 shows screens as the whole screen, and line 4 also writes the screen's text.
Text and Ink explains this message.
ownedBandRow
Message: Screen row 11 is set by both lines 8 and 11.
Text and Ink explains how each row gets one source.
ownedBandChoice
Message: The screen bands on lines 9 and 10 choose different screens.
Text and Ink explains how the whole picture chooses one screen.
ownedBandScroll
Message: The changing scroll on line 12 crosses the band on line 8 and the region on line 11.
Text and Ink explains why a changing scroll needs a qualified row-boundary change.
ownedScreensBank
Message: The 16 screens in screens (16,384 bytes) and the program's character sets and sprite shapes need 16,384 bytes together, and they don't fit in one stretch of 16,384 bytes beside this program's code and data.
Text and Ink explains this message.
beamLate
Message: Line 6 writes colors the screen is showing, and a row of them can change only after the screen has drawn it. On PAL the wait for row 24 ends about 18,910 cycles into the frame and the work from there takes 4,836 more, so the frame needs 23,446 cycles and holds 19,656: 3,790 cycles over budget.
Text and Ink explains this message.
beamAfterEnd
Message: Line 15 writes colors the screen is showing, but on PAL the frame can come to the wait for row 0 about 19,749 cycles in, and the screen starts its next picture at 19,656.
After the picture ends the wait can no longer tell that the screen has drawn the row, so it would hold the frame for a whole picture more. A frame that must begin after picture row 205 so its last row can finish (see beamLate) may not come to a write of an upper row after the screen has begun the next picture. Write that row before the rows that come after it on the screen.
Text and Ink explains this message.
paddleDeselected
Message: The interrupt routine on line 6 stores to the port that picks which pair of paddles the chip reads, and this program reads a paddle.
The chip gives a paddle reading only after it has read the same pair for two of its 512-cycle updates, about 1,000 cycles. A store from a routine that can run at any line can change the pair just before the program reads. Keep the top two bits of the stored value at 01 in the routine, or read the keys and sticks somewhere else than a routine.
Assembly explains this message.
deferredLate
Message: The cells kept for the end of the frame are stored about 3,600 cycles into it on early NTSC, and the screen starts drawing at 3,458.
The cells a program writes at places known when it is built, and never reads back, are stored together when the next frame begins, while the border is showing. When there are so many that the screen would start drawing before they are stored, the compiler refuses the program and names the first.
Text and Ink explains this message.
spritesLate
Message: The sprites and their colors are stored about 2,700 cycles into the frame on early NTSC, and a sprite near the top of the screen starts drawing at 2,614.
A program that shows a screen of its own stores its sprites, their shapes and their colors together at the top of the next frame, while the border is showing, so that no picture shows a sprite half changed. When there are so many that a sprite near the top of the screen would start before they are stored, the compiler refuses the program and names the last of them.
Sprites explains this message.
windowChoice
Message: System.screen.columns shows 40 or 38, not 39.
Scroll and Window explains this message.
windowRaster
Message: A changing vertical scroll can't share this raster setup.
Scroll and Window explains this message.
bitmapWindow
Message: System.screen.scroll moves text, and this program shows a canvas (line 1).
Scroll and Window explains this message.
Pictures and Files
These messages appear when pixel art rows or external asset files don't match the shape the compiler expects.
pixelAsset
Message: These Shape pixels can't be used: give it a constant list of pixel rows or bytes.
Pictures and Fonts explains this message.
fontBuilderConstant
Message: shifting must be known when the program compiles.
Fonts Built from the Machine's Letters explains this message.
fontCharacterIndex
Message: This font's characters are not known when the program compiles.
Fonts Built from the Machine's Letters explains this message.
assetFile
Message: The file ship.bin can't be used: the project holds no asset files; add it under the project root.
Include and Project Files explains this message.
notSerializable
Message: Tone is not disk-serializable.
Disk Drives explains this message.
saveBinding
Message: A save that gives Result of Receipt? follows its value, so it belongs in a binding.
Disk Drives explains this message.
saveEveryFrame
Message: ticks can change every frame, and each change starts a disk write.
Disk Drives explains this message.
streamCapacity
Message: A file stream read needs a constant buffer capacity between 1 and 255.
Disk Drives explains this message.
Changing Arguments
mutParameter
Only a function can take a mut parameter; use a fn for the update instead of a work member or an op.
mutArgumentMark
Write mut at the call for a changing parameter, and remove it for an ordinary value parameter.
mutArgumentPlace
Pass a var, or a field, element or slice of one. A constant, binding, ordinary parameter, device output or call result cannot be changed this way.
mutArgumentType
A changing place needs exactly the parameter's type. Use a local var of that type and assign it back after the call if conversion is needed.
mutArgumentBinding
Call a function with changing arguments in a when handler. A binding calculates a value, and a work member captures values for later turns.
mutArgumentOverlap
Two changing arguments, or one and a changing receiver, might be the same place. Pass different places, prove the indices differ with an if, or pass the whole list once.
Mutable Parameters explains these rules.
Callable Values
callableType
The callback's signature does not fit the required slot, or a value call has the wrong argument shape. The message gives the required and supplied types; check input domains, result domains, list sizes, optional presence and nested signatures. Function Types explains the safe input and result directions.
callableContext
Give the callback a concrete function type, or supply the positional inputs its signature requires. The detail identifies unresolved inference, a conflicting signature, an unknown callback choice or a value call using declaration labels. Functions as Values explains concrete specialization and Callable Values explains invocation.
callableEffect
The named declaration cannot supply a pure function value. Use a pure free value function or an explicit pure function expression; ops, work, mutating functions, action-only declarations and bare member or built-in references do not fill that slot. See Functions as Values.
callableLifetime
The captured callback would outlive one of its copied local environments. Keep it in synchronous immutable locals, arguments or forwarding results while its creating call remains live; do not return a new captured environment, retain it in a variable, or keep it for use after a wait. Synchronous Snapshot Captures shows an admitted forwarding example.
callableOperation
A callable or a value containing callables is being used in an unsupported operation, such as comparison or temporal retention. This also applies to callback components inside lists, structs and optionals; wrapping a callback does not make the operation valid. Function Types lists the supported data positions and exclusions.
Callable Byte Exports
exportSignature
Write one or two Number<u8> value parameters and a Number<u8> result on a named free export fn. Methods, callbacks, mutable parameters and inferred signatures have no external byte calling convention.
exportTotal
The calculation or a reachable helper can fail for an allowed byte input, or needs state or effects that an external caller cannot supply. Use ranges the compiler can prove safe or explicit wrapping/clamping arithmetic. A pure calculation alone does not guarantee that every call returns.
Keys That Need a Long Program
You will only bump into one of these messages if your program grows past a hardware or compiler table limit.
nestingBlock: blocks nested more than 16 deep, such as seventeenifstatements inside one another. Lines explains the rule.drawingCount: a canvas'sdrawingslist with more than 255 places. Drawings explains the rule.outlineSize: outlines in onedrawingslist that hold more than 85 points together. Drawings explains the rule.textOverlapBudget: so many text bindings on one row, such as 120, that the screen cannot redraw the row within a single frame. Text Placement explains the rule.pageTables: regions that hold more than 255 rows of text together, or rows that the program's regions and cases break into more than 255 runs. Regions and Printing explains the rule.ownedBandTables: bands beside so many regions or selectable screens that their row destinations exceed 255. Text and Ink explains the rule.pageMatrix: a printing program that is too large to keep the hidden screen copy that printing draws into. Printing explains the rule.bitmapShapes: a canvas program that uses more than 64 distinct sprite shapes. Sprites explains the rule.drawPiece: a drawing whose largest step takes more cycles than the frame leaves for it. Drawing Over Frames explains the rule.spritesLate: so many sprites, shapes and sprite colors that they cannot all be stored at the top of the frame before a sprite near the top of the screen starts. Sprites explains the rule.deferredLate: so many cells written at fixed places, and never read back, that they cannot all be stored before the screen starts drawing. Text and Ink explains the rule.assetPlacement: a program whose screen, character sets, and sprite shapes do not fit beside its code and data. Pictures and Fonts explains the rule.
Keys No Program Reaches
These keys exist as internal guardrails in the compiler, though no ordinary program reaches them today.
extraOnLineandexpressionNeeded: the line reader catches an extra word or a missing value withunexpectedfirst.caseStartLate: a case that takes more than a frame to start, whose screen would come back too late in the frame. Because the work before a case'smatchis short today, the screen always comes back in time.librarySource,libraryPlacementandlibraryBoundary: these diagnose explicit callable-library builds, including unsupported source declarations, invalid or insufficient memory reservations and unbounded machine effects. Ordinary application compilation does not request that artifact.assertionPlacement: a checker guard for assertions in bodies or declaration cases. The line reader refuses these earlier withdirectivePlacement, before ordinary source can reach this guard. Compile-Time Assertions explains the rule.frameUnproved: a frame whose work the compiler cannot count, with noasmblock of yours to explain it. It is a gap in the compiler's own counting, and the message asks you to report the program.malformedEncoding: bytes that are not valid UTF-8. The file reader catches them with their line and column before any program text exists, so the line reader never sees them. Source Text explains the rule.unicodeUnsupported: a computer whose text library is older than Unicode 15, which cannot compare names outside ASCII the way every other computer does.internal: an unexpected fault inside the compiler itself rather than in your program. The message asks you to share the program that triggered it.
partialHead requires an area declaration such as partial const log = System.screen.region(row: 12). partialCanvas identifies a canvas shape whose complete-row path is still unfinished, such as mixed picture/outline lists, multicolor or case changes. Hires canvases with placed pictures and whole-screen outline-only canvases outside cases and partial text regions are available now.