Start with a block-local loop
A statement-level asm { ... } block uses 64tass-style instruction syntax. ZeroPage extracts the block before Zig validates the surrounding source. This loop uses X, modifies the mutable byte color, and writes to the VIC-II border register.
const c64 = @import("c64");
export fn main() void {
c64.console.clear();
var color: u8 = 2;
asm {
ldx #3
brighten:
inc @color
dex
bne brighten
lda @color
sta $d020
}
c64.console.print("BORDER {x}\n", .{color});
}
Expect BORDER 05 and a green border. brighten: belongs to this block. Another block may reuse the label. Branches target labels inside their own block and have a displacement of −128 to +127 bytes from the next instruction. jmp label also stays inside the block.
Parameters, locals, enums, and flattened record fields
@delta names a byte parameter cell. @result names a mutable byte local. Use @actor_pos_x for the flattened byte field actor.pos.x. This works for a by-value record parameter and a local record. The enum field uses the byte tag from @mode. The function returns through normal ZeroPage source.
const c64 = @import("c64");
const Mode = enum(u8) { normal = 1, bright = 2 };
const Position = struct { x: u8, y: u8 };
const Actor = struct { pos: Position, mode: Mode };
fn adjustedX(actor: Actor, delta: u8) u8 {
var result: u8 = 0;
asm {
lda @actor_pos_x
clc
adc @delta
sta @result
}
return result;
}
export fn main() void {
c64.console.clear();
var actor = Actor{ .pos = Position{ .x = 3, .y = 4 }, .mode = .normal };
var mode: Mode = .bright;
asm {
inc @actor_pos_x
lda @mode
sta @actor_mode
}
const x = adjustedX(actor, 1);
c64.console.print("X {x} MODE {x}\n", .{ x, actor.mode });
}
Expect X 05 MODE 02. Use u8, i8, bool, or byte enums and byte fields. Keep Boolean and enum values valid. Treat parameter cells as the callee's copies. Plain scalar const bindings and word, pointer, array, or whole-record operands are outside this documented interface. Use ZeroPage code to split wider inputs or prepare pointer accesses. #@delta is invalid because a variable cell is not an immediate.
String addresses, indexed data, and length cells
@source.data,y reads a byte using Y. @msg.data,y writes the mutable buffer. #@source.len is an immediate length, while @msg.len is a runtime cell. A buffer's capacity is fixed. An assembly copy must respect it and update the length.
const c64 = @import("c64");
const source = "asm string ok\n";
export fn main() void {
c64.console.clear();
c64.console.print("inline asm strings\n", .{});
var msg = c64.string.buffer(32);
asm {
ldy #0
copy:
lda @source.data,y
sta @msg.data,y
iny
cpy #@source.len
bne copy
lda #@source.len
sta @msg.len
lda #33
sta @msg.data+12
}
c64.console.puts(msg);
c64.console.print("asm string done\n", .{});
c64.vic.border = 5;
}
ldx #<@source.data
ldy #>@source.data
The same low/high address forms work for a mutable buffer. An offset such as @msg.data+12 remains assembler arithmetic. Constant data is read-only. #@msg.len and bare string operands are rejected.
To read indirectly, reserve a zero-page pair, initialize it with the low and high address bytes, then load through ($30),y. This example saves and restores the borrowed BASIC bytes itself. The register wrapper preserves CPU state, and the compiler's zero-page cleanup covers its own claims.
const c64 = @import("c64");
const text = "A";
memory {
zero_page {
profile = .kernal;
reserve at 0x30 size 2;
restore_basic = true;
interrupts = .system;
}
}
export fn main() void {
c64.console.clear();
var glyph: u8 = 0;
var saved_lo: u8 = 0;
var saved_hi: u8 = 0;
asm {
lda $30
sta @saved_lo
lda $31
sta @saved_hi
lda #<@text.data
sta $30
lda #>@text.data
sta $31
ldy #0
lda ($30),y
sta @glyph
lda @saved_lo
sta $30
lda @saved_hi
sta $31
}
c64.console.print("GLYPH {x}\n", .{glyph});
}
What the compiler saves and restores
The wrapper combines clobbers across the whole block. The following table counts wrapper bytes on the hardware stack. A subroutine's return address, nested calls, and interrupts consume additional stack space.
| Instruction example | Saved state | Bytes |
|---|---|---|
sta $d020, nop | None | 0 |
inc @value, cmp #5, clc | P | 1 |
lda #5, asl a | P and A | 2 |
ldx #3 or ldy #3 | P, A, and the changed index register | 3 |
Both index registers or any external jsr | P, A, X, Y | 4 |
TXA and TYA use A to push the index values. Restores run in reverse order. PLP is last because the preceding pulls and transfers can change flags. Here is the generated wrapper for a KERNAL CHROUT call:
php
pha
txa
pha
tya
pha
lda #$41
jsr $ffd2
pla
tay
pla
tax
pla
plp
Prepare call registers and consume results inside the same block. Store a useful result to a source cell before fallthrough. RAM, I/O, and ROM workspace writes survive register restoration. The host fixture primes A, X, Y, and P and checks them after both a clobbering block and an external call. Register preservation fixture. Reserve assembly-owned zero-page bytes explicitly and account for IRQ and ROM requirements. A block that writes the processor port also owns the resulting bank mapping.
Inspect the assembly wrapper in your own program
Generate assembly for the border example and find the loop that increments color. The block changes A, X, and status. The wrapper saves those before the first instruction and restores them after the store to $d020. If you single-step the PRG in VICE, compare the registers just before the wrapper and just after it. The border remains green because the wrapper restores CPU state while the device write has already happened.
Pass a word through byte-sized operands
Give the two bytes explicit names in a by-value record. The block reads @counter_low and @counter_high and writes two mutable local cells. CLD selects binary arithmetic and CLC clears incoming carry. The first ADC produces the low byte and leaves carry set on overflow. STA and LDA leave carry intact, so ADC #0 propagates it into the high byte. At fallthrough the wrapper restores incoming flags, including decimal mode and carry. The two stores are the result.
const c64 = @import("c64");
const Counter = struct { low: u8, high: u8 };
fn addByte(counter: Counter, delta: u8) u16 {
var low: u8 = 0;
var high: u8 = 0;
asm {
cld
clc
lda @counter_low
adc @delta
sta @low
lda @counter_high
adc #0
sta @high
}
return (@as(u16, high) << 8) | @as(u16, low);
}
export fn main() void {
c64.console.clear();
const result = addByte(Counter{ .low = 0xff, .high = 0x12 }, 1);
c64.console.print("COUNTER {x16}\n", .{result});
}
Expect COUNTER 1300. The wrapper function widens the result bytes before shifting and joining them. For a routine that consumes a genuine pointer, use the address and indirect forms.
Capture the result of a KERNAL call
GETIN at $ffe4 returns the next PETSCII byte from the keyboard buffer when the keyboard is the input channel. A zero result means no byte is ready. JSR causes ZeroPage to save A, X, Y, and status. Capture A with STA @key inside the block, then return the byte through ordinary ZeroPage code. If a ROM routine reports a condition in flags, branch on those flags inside the block and store a Boolean byte before fallthrough.
const c64 = @import("c64");
fn readKey() u8 {
var key: u8 = 0;
asm {
jsr $ffe4
sta @key
}
return key;
}
export fn main() void {
c64.console.clear();
c64.console.print("PRESS A KEY\n", .{});
var key: u8 = 0;
while (key == 0) {
key = readKey();
}
c64.console.print("KEY {x}\n", .{key});
}
With KERNAL visible and the standard keyboard input selected, press A at the prompt. The unshifted A key on the default C64 keyboard configuration prints KEY 41. For ordinary keyboard reads, c64.keyboard.readPetscii() provides the built-in operation. The assembly example exposes the register boundary you also use with other firmware calls.
Pass a filename and capture the KERNAL carry flag
Prepare the inputs and consume the result inside one assembly block. For SETNAM, A holds the filename length and X/Y hold its address, low byte first. The string binding supplies all three without a generated label name. SETLFS selects logical file 1, disk device 8, and secondary address 0. With this setup, LOAD uses the destination in X/Y, here $9000. Commodore Programmer's Reference Guide, KERNAL routines transcription
const c64 = @import("c64");
const filename = "tile";
memory {
region staging: c64 at 0x9000 size 0x0100;
}
fn loadTile() bool {
var loaded: bool = false;
asm {
lda #@filename.len
ldx #<@filename.data
ldy #>@filename.data
jsr $ffbd
lda #1
ldx #8
ldy #0
jsr $ffba
lda #0
ldx #$00
ldy #$90
jsr $ffd5
bcs done
lda #1
sta @loaded
done:
}
return loaded;
}
export fn main() void {
c64.console.clear();
if (loadTile()) {
const tile: *volatile u8 = @ptrFromInt(0x9000);
c64.console.print("TILE {x}\n", .{tile.*});
c64.vic.border = 5;
} else {
c64.console.print("LOAD FAILED\n", .{});
c64.vic.border = 2;
}
}
LOAD reports an error with carry set. Branch immediately with BCS. The error path leaves loaded false, and the success path stores 1 into the Boolean cell. Both paths fall through the wrapper, which restores A, X, Y, and status. The source code reads the result cell after that restoration. KERNAL's writes to workspace and destination RAM survive.
Boot the disk with the one-byte tile to see TILE 55. Boot the version with only boot to see LOAD FAILED. The example expects a known one-byte PRG on device 8 and leaves KERNAL and I/O visible. The staging declaration reserves RAM from other compiler claims. KERNAL LOAD can write beyond that reservation if the input is larger, so use the supplied payload when following the exercise.
Build and boot the two KERNAL load disks
Complete checked load source · Follow a DLL through KERNAL staging into REU
External calls, terminal jumps, and rejected forms
External jsr accepts a numeric address or an assembler-resolved symbol and must return with the hardware stack balanced. Local jsr, inline rts/rti/brk, and stack manipulation such as pha or txs are rejected. Keep directives, includes, macros, and data declarations outside the inline form. Use a static-frame function. Stack frames and DLL exports have stricter body rules.
asm {
jmp $c80c
}
This single-instruction absolute block transfers to a documented resident vector and bypasses normal ZeroPage return. Supply the machine state required by the vector. Prepare required memory in ZeroPage. A preceding normal block restores registers and flags at fallthrough. Indirect jumps, external symbolic jumps, and additional instructions in the terminal block are rejected.
Reach a distant label within an assembly block
A conditional branch encodes a signed byte displacement measured from the instruction after the branch. If beq finish has to skip more than 127 bytes, invert the condition to skip over a nearby absolute jmp. Both labels remain local to the block. A compiler save wrapper surrounds the block, so its pushes do not change the distance between these two local instructions.
bne continue_work
jmp finish
continue_work:
; the long fallthrough path goes here
finish:
In the original, the equal case reaches finish. In the rewritten version, the equal case falls through to jmp finish, and the unequal case branches to continue_work. Inspect the assembled instructions if you are budgeting cycles. Out-of-range branch fixture · Label and jump rules