Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Syntax

The examples on this page are interactive: edit the source and click Assemble to build it in your browser (powered by the WebAssembly build of nessemble). Assembled bytes are shown as a hex dump and can be downloaded.

LDX #$08 loop: DEX BNE loop BRK

Numbers

Binary, decimal, octal, hexadecimal, and ASCII character are all valid numbers.

BaseExample AExample B
Binary%0100000101000001b
Decimal6565d
Octal0101101o
Hexadecimal$4141h
ASCII char'A'

Symbols

Mathematical Operators

SymbolDescription
+Add
-Subtract
*Multiply
/Divide
**Exponent
&Bitwise AND
|Bitwise OR
^Bitwise XOR
>>Shift right
<<Shift left
%Modulo

Comparison Operators

SymbolDescription
==Equals
!=Not equals
<Less than
>Greater than
<=Less than or equals
>=Greater than or equals

Unary Operators

SymbolDescription
-Negate
~Bitwise NOT (complement)
!Logical NOT (1 if zero, else 0)

A unary operator is written directly before its operand, anywhere an expression is allowed: data, operands (#-1, <-off), definitions, .if, .for bounds, macro and custom pseudo-instruction arguments. Unary operators bind tighter than any binary operator, and they may be stacked: - -4 is 4, !!x is 0 or 1, and ~-1 is 0.

Example:

.db -4
.dw -40
    LDA #-1
.db ~$0F

Output:

00000000  fc d8 ff a9 ff f0                                 |......|
00000006

Try it:

.db -4 .dw -40 LDA #-1 .db ~$0F

! applies to its operand only: !FLAG == 0 is (!FLAG) == 0. To negate a comparison, parenthesise it: !(FLAG == 0).

Evaluation order

Binary operators all share one precedence level and group strictly right to left: 20 - 2 - 1 is 20 - (2 - 1), which is 19, and 2*3 - 1 is 2 * (3 - 1), which is 4. Use parentheses to group otherwise. Unary operators sit above all of them, so 4 - -2 is 6 and -2 * 3 is (-2) * 3, which is -6.

Signed values in data

Expression values are signed integers. A value is narrowed to the byte or word it is stored in, so .db -4 emits $FC and .dw -40 emits $FFD8. A byte accepts -128 to 255 and a word -32768 to 65535; anything outside warns (see Diagnostics) and emits the narrowed value anyway.

~ complements every bit, so ~$80 is -129, outside the byte range: AND #~$80 warns. Write AND #LOW(~$80) to keep only the low byte.

.db 1 -2 is one value. It reads as 1 - 2 and emits a single $FF. Separate list items with commas: .db 1, -2.

:- - 1 is not (:-) - 1. The - run after a colon is all part of the anonymous reference, so :- - 1 reads as :-- followed by a stray 1. Write (:-) - 1 or :- + -1.

Special

SymbolDescription
->Accessor (functions like +)

-> belongs to its operand, so -sprite->coord_x is -(sprite->coord_x).

Labels

Named

Named label declarations must be in the follow format:

NAME:
  • NAME - Label name, required.

A label is a line of its own: anything after the colon other than a comment is an error (foo: .db 1 reports "a label must be on a line of its own"). Write the instruction or data on the next line. Defining the same name twice is allowed — the last definition wins — but warns (see Diagnostics).

Example:

    LDX #$08
loop:
    DEX
    BNE loop
    BRK

Output:

00000000  a2 08 ca d0 fd 00                                 |......|
00000006

Try it:

LDX #$08 loop: DEX BNE loop BRK

A label that names a subroutine can carry its calling convention — the registers it takes, returns, and destroys — in comments the tooling reads. See Documenting routines.

Local

A label whose name starts with @ is local to the nearest named label above it in the same file. Each routine can reuse names like @loop and @done without them colliding:

@NAME:
  • NAME - Local label name: one or more letters, digits or _, required.

Inside its scope — from the named label that opens it down to the next one — a local is written @NAME, and may be referenced before or after its definition. From anywhere else, write the qualified name ROUTINE@NAME.

Example:

clear_x:
    LDX #$08
@loop:
    DEX
    BNE @loop
    RTS
clear_y:
    LDY #$08
@loop:
    DEY
    BNE @loop
    JMP clear_x@loop

Output:

00000000  a2 08 ca d0 fd 60 a0 08  88 d0 fd 4c 02 00        |.....`.....L..|
0000000e

Try it:

clear_x: LDX #$08 @loop: DEX BNE @loop RTS clear_y: LDY #$08 @loop: DEY BNE @loop JMP clear_x@loop

The rules:

  • What opens a scope. Any named label that is assembled opens one, including a pasted row\i: in a .for body. A label inside a false .if opens nothing, and neither do anonymous labels (:), .rs reservations, constants, .org, .phase or .segment. A label a macro builds with \@ (name\@:) is private to the expansion and opens no scope either, so use name\@: for a macro's internal labels.
  • Locals are labels only. @len = 4, a bare @flag, and @buf .rs 1 are errors: give a constant or variable a global name. A qualified name can only be referenced; p1@x: is an error that says to write @x: under p1.
  • Defining a local twice in one scope is an error — not the duplicate-symbol warning a global gets, because a local collision is always a mistake.
  • Includes. An .included file starts with no scope, so a local before its first named label is an error, and the includer's scope resumes after the .include. Locals never cross files; reference one in another file by its qualified name.
  • Macros. A local a .macrodef body defines itself is private to each expansion, so a macro with an internal @spin loop can be used twice in one routine. A body reference to a local it does not define, such as BEQ @done, resolves in the caller's scope. To hand a macro the caller's local, pass it as an argument (.macro jump_to, @done). Private locals are listed by -l only with --mlist, as parent@name\@N.
  • .for bodies. A plain @x: in a body would be defined once per iteration in the same scope, so it is rejected — write @x\i: for one label per iteration (@x0, @x1, …). The exception is a body that defines a pasted label first (row\i:): each iteration then has its own scope, and a plain @x: after it is fine.
  • Everything that names a symbol resolves locals the same way: operands, data, .for bounds, .ifdef, BANK(@x), -> chains, and .table keys.

Why not anonymous labels? :+ and :- count labels, so inserting a label between a branch and its target silently retargets it. A local has a name, so it can't be miscounted.

Migrating from global @ labels. Before local labels, an @name label was an ordinary global, and two routines' @loops silently cross-linked. Code that relied on reaching an @ label from another routine now fails with an error that suggests the qualified name: `@x` is not defined in `p2`; did you mean `p1@x`?. A constant spelled with @ needs a global name.

Temporary

Temporary/un-named labels may also be declared by placing only a colon.

:

To jump to a temporary label, the direction and count of the jumps must be given.

JMP :[+-]

[+-] - Direction, required.

N-number of +s means to jump to the temporary label that is N temporary labels further down in the code.

N-number of -s means to jump to the temporary label that is N temporary labels further up in the code.

Example:

    LDX #$08
:
    DEX
    BNE :-
    BRK

Output:

00000000  a2 08 ca d0 fd 00                                 |......|
00000006

Try it:

LDX #$08 : DEX BNE :- BRK

The -s after a colon all belong to the reference, even with spaces between them: :- - 1 is :-- followed by a stray 1. To subtract from a backward reference, write (:-) - 1 or :- + -1 (see Unary Operators).

Mnemonics

All 56 mnemonics are supported:

MnemonicDescription
ADCAdd with Carry
ANDBitwise AND with Accumulator
ASLArithmetic shift left
BITTest bits
BCCBranch on Carry clear
BCSBranch on Carry set
BEQBranch on equal
BMIBranch on minus
BNEBranch on not equal
BPLBranch on plus
BRKBreak
BVCBranch on Overflow clear
BVSBranch on Overflow set
CLCClear Carry
CLDClear Decimal
CLIClear Interrupt
CLVClear Overflow
CMPCompare Accumulator
CPXCompare X register
CPYCompare Y register
DECDecrement memory
DEXDecrement X register
DEYDecrement Y register
EORBitwise exclusive OR
INCIncrement memory
INXIncrement X register
INYIncrement Y register
JMPJump
JSRJump to subroutine
LDALoad Accumulator
LDXLoad X register
LDYLoad Y register
LSRLogical shift right
NOPNo operation
ORABitwise OR with Accumulator
PHAPush Accumulator
PHPPush processor status
PLAPull Accumulator
PLPPull processor status
ROLRotate left
RORRotate right
RTIReturn from Interrupt
RTSReturn from subroutine
SBCSubtract with Carry
SECSet Carry
SEDSet Decimal
SEISet Interrupt
STAStore Accumulator
STXStore X register
STYStore Y register
TAXTransfer Accumulator to X register
TAYTransfer Accumulator to Y register
TSXTransfer Stack Pointer to X register
TXATransfer X register to Accumulator
TXSTransfer X register to Stack Pointer
TYATransfer Y register to Accumulator

Read more about 6502 opcodes here.

In addition, 24 illegal/undocumented mnemonics may be used when assembled with the -u, --undocumented flag.

MnemonicDescription
AACAND with Accumulator
AAXAND X register with Accumulator
ARRAND with Accumulator
ASRAND with Accumulator
ATXAND with Accumulator
AXAAND X register with Accumulator
AXSAND X register with Accumulator
DCPSubtract 1 from memory
DOPNo operation (x2)
ICSIncrease memory by 1
KILStop program counter
LARAND memory with stack pointer
LAXLoad Accumulator and X register
NOPNo operation
RLARotate one bit left in memory
RRARotate one bit right in memory
SBCSubtract with Carry
SLOShift left one bit in memory
SREShift right one bit in memory
SXAAND Y register with the high byte of address
SYAAND Y register with the high byte of address
TOPNo operation (x3)
XAAUnknown
XASAND X register with Accumulator

Read more about undocumented 6502 opcodes here.

Addressing Modes

ModeExample
ImpliedRTS
AccumulatorROL A
ImmediateLDA #$42
ZeropageSTA <$42
Zeropage, XEOR <$42, X
Zeropage, YLDX <$42, Y
AbsoluteSTA $4200
Absolute, XEOR $4200, X
Absolute, YLDX $4200, Y
IndirectJMP [$4200]
Indirect, XLDA [$42, X]
Indirect, YSTA [$42], Y
RelativeBEQ label

nessemble uses square brackets [] instead of parentheses () in its addressing modes because the latter are used to indicate precedence in mathematical operations.

Read more about 6502 addressing modes here.

Functions

FunctionDescription
HIGH()Get high byte of address
LOW()Get low byte of address
BANK()Get bank of address

Pseudo-Instructions

Pseudo-InstructionDescription
.asciiConvert ASCII string to bytes
.assertFail the build unless an expression holds
.byteAlias for .db
.checksumCalculate crc32 checksum
.chrSet CHR bank index
.colorConvert hex color to NES color
.dbDefine 8-bit byte(s)
.defchrDefine CHR tile
.dephaseEnd a .phase block
.dwDefine 16-bit word(s)
.elseElse condition of an .if/.ifdef/.ifndef statement
.endenumEnd .enum
.endforEnd a .for block
.endifEnd .if/.ifdef/.ifndef statement
.endmEnd .macrodef
.endtableEnd a .table
.enumStart a block of sequential constants
.errorFail the build with a message
.fillFill with bytes
.fontGenerate font character tile
.forRepeat a block, unrolled
.hibytesOutput only the high byte of 16-bit word(s)
.ifTest if condition
.ifdefTest if variable is defined
.ifndefTest if variable has not been defined
.incbinInclude binary file
.includeInclude assembly file
.incpalInclude palette from PNG
.incpngInclude PNG
.incrleInclude binary data to be RLE-encoded
.incwavInclude WAV
.ines2Emit a NES 2.0 header
.ines4scriNES four-screen VRAM flag
.inesbatiNES battery / persistent memory flag
.ineschriNES CHR count
.ineschrnvramNES 2.0 battery CHR-RAM size
.ineschrramNES 2.0 CHR-RAM size
.inesconsoleNES 2.0 console type
.inesexpansionNES 2.0 default expansion device
.inesmapiNES / NES 2.0 mapper number
.inesmiriNES mirroring
.inesmiscromNES 2.0 miscellaneous ROM count
.inespc10iNES PlayChoice-10 flag
.inesprgiNES / NES 2.0 PRG count
.inesprgnvramNES 2.0 battery PRG-RAM size
.inesprgramiNES / NES 2.0 PRG-RAM size
.inessubmapNES 2.0 submapper number
.inestimingNES 2.0 CPU/PPU timing
.inestrniNES trainer include
.inestviNES / NES 2.0 TV system
.inesvsiNES VS Unisystem flag
.inesvshwNES 2.0 VS System hardware type
.inesvsppuNES 2.0 VS System PPU type
.lobytesOutput only the low byte of 16-bit word(s)
.macroCall macro
.macrodefStart macro definition
.orgOrganize code
.outPrint a message while assembling
.phaseAssemble code for a different run-time address
.prgSet PRG bank index
.randomOutput random byte(s)
.rssetSet initial value for .rs declarations
.rsReserve space for variable declaration
.segmentSet code segment
.tableCheck an indexed table's entries against their keys
.wordAlias for .dw

.ascii

Convert ASCII string to bytes.

Usage:

.ascii "STRING"[(+/-)NUMBER]
  • "STRING" - String, required. ASCII string to turn into bytes. Must be within quotes.
  • (+/-)NUMBER - Number, optional. Amount to increase/decrease ASCII values.

Example:

.ascii "When, in disgrace with fortune and men's eyes"

Output:

00000000  57 68 65 6e 2c 20 69 6e  20 64 69 73 67 72 61 63  |When, in disgrac|
00000010  65 20 77 69 74 68 20 66  6f 72 74 75 6e 65 20 61  |e with fortune a|
00000020  6e 64 20 6d 65 6e 27 73  20 65 79 65 73           |nd men's eyes|
0000002d

Try it:

.ascii "When, in disgrace with fortune and men's eyes"

The +/- operators may also be used to increase/decrease the output.

Example:

.ascii "I all alone beweep my outcast state"-32

Output:

00000000  29 00 41 4c 4c 00 41 4c  4f 4e 45 00 42 45 57 45  |).ALL.ALONE.BEWE|
00000010  45 50 00 4d 59 00 4f 55  54 43 41 53 54 00 53 54  |EP.MY.OUTCAST.ST|
00000020  41 54 45                                          |ATE|
00000023

.assert

Fail the build unless an expression holds.

Usage:

.assert EXPRESSION[, "MESSAGE"]
  • EXPRESSION - Expression, required. The build fails when it evaluates to 0.
  • "MESSAGE" - String, optional. Shown when the assertion fails. Must be on the same line.

An assertion emits nothing, moves nothing and defines nothing: a program assembles to the same bytes with or without it. It is checked once, after the last pass, against the final symbol table, so it can name a label defined later in the file, and a .phased label reads its run-time address.

Example:

KIND_LAST = $07
ptr_table:
    .dw kind_0, kind_1, kind_2, kind_3, kind_4, kind_5, kind_6
kind_table:
    .assert (kind_table - ptr_table) == (2 * (KIND_LAST + 1)), "one pointer per KIND_*"

Output:

Error in `tables.asm` on line 5: assertion failed: one pointer per KIND_* — `(kind_table - ptr_table) == (2 * (KIND_LAST + 1))` is 0 ($0E == $10; kind_table = $0E, ptr_table = 0, KIND_LAST = 7)

The failure quotes the expression as written. In parentheses it shows both sides of a top-level comparison, then the value of each name the expression reads (up to eight). Values from 0 to 9 and negative values print in decimal, others in hexadecimal.

Binary operators all share one precedence and group right to left, so A + B == 0 means A + (B == 0). Write the parentheses: the values in the failure show what each side came to.

A constant assigned more than once is read at its final value, the value the last pass emits for it.

A name the assertion uses that is never defined is its own error (Symbol `x` in `.assert` was not defined), with no failure message.

Rules:

  • In a .macrodef body, \1, \# and \@ in the message are replaced by the argument as written at the call, the argument count and the unique number. A failure is reported at the body line, with a note naming each call. No other string in a macro body is rewritten.
  • In a .for body, \i, \j and \k in the message are replaced by the counters. Each iteration is checked, but a failing line is reported once, naming the first iteration that failed.
  • In a false .if branch the assertion is skipped, however deeply it is nested. It is checked only when every enclosing .if is true.
  • The CLI stops at the first error. The language server reports every failing assertion at once.

Try it:

SIZE = 4 .assert SIZE == 4, "SIZE changed" .db SIZE

.checksum

Calculate crc32 checksum.

Usage:

.checksum LABEL
  • LABEL - Label, required. Label at which to start generating the checksum.

Example:

start:
    LDA #$01
    STA <$02
    .checksum start

Output:

00000000  a9 01 85 02 b8 1f ee 86                           |........|
00000008

The checksum is b8 1f ee 86.

Checksums may only be performed on preceding data.

Try it:

start: LDA #$01 STA <$02 .checksum start

.chr

Set CHR bank index.

Usage:

.chr NUMBER
  • NUMBER - Number, required. CHR bank index.

Example:

.chr 0

CHR banks are 2K bytes (0x2000) in size.

.color

Convert hex color to NES color.

Finds the closest valid NES color to the given hex color.

Usage:

.color NUMBER[, NUMBER, ...]
  • NUMBER - Number, required. At least one number is required.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.color $FF0000

Output:

00000000  16                                                |.|
00000001

Read more about the NES color palette here.

In an editor connected to the language server, hovering .color previews the palette entries the whole argument list maps to, and hovering a single argument previews just that color.

Try it:

.color $FF0000

.db

Define 8-bit byte(s).

Usage:

.db NUMBER[, NUMBER, ...]
  • NUMBER - Number, required. At least one number is required.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.db $12, $34

Output:

00000000  12 34                                             |.4|
00000002

Try it:

.db $12, $34

A trailing comma continues the list onto the next line, so a long run of bytes can be wrapped across several indented lines:

.db $00, $01, $02, $03,
    $04, $05, $06, $07

The same line-continuation rule applies to every comma-separated data directive (.dw, .fill, .color, .hibytes, .lobytes, and .defchr).

Negative values are stored as two's complement (see Unary Operators):

.db -1, ~$0F

Output:

00000000  ff f0                                             |..|
00000002

.defchr

Define CHR tile.

Only numbers from 0-3 may be used: 0 representing black, 1 dark grey, 2 light grey, and 3 representing white.

Usage:

.defchr XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX,
        XXXXXXXX
  • XXXXXXXX, - Number, required. Must be exactly 8 numbers of 8-characters each.

Example:

.defchr 333333333,
        300000003,
        300000003,
        300000003,
        300000003,
        300000003,
        300000003,
        333333333

Output:

00000000  ff 01 01 01 01 01 01 ff  ff 01 01 01 01 01 01 ff  |................|
00000010

Read more about PPU pattern tables here.

Try it:

.defchr 333333333, 300000003, 300000003, 300000003, 300000003, 300000003, 300000003, 333333333

.dephase

End a .phase block. Labels defined after .dephase revert to their physical load address. A bank or segment switch (.prg, .chr, .segment) also ends any active phase.

Usage:

.dephase

.dw

Define 16-bit word(s).

Usage:

.dw NUMBER[, NUMBER, ...]
  • NUMBER - Number, required. At least one number is required.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.dw $1234, $5678

Output:

00000000  34 12 78 56                                       |4.xV|
00000004

Try it:

.dw $1234, $5678

A negative value is stored as a 16-bit two's complement word:

.dw -40

Output:

00000000  d8 ff                                             |..|
00000002

.else

Else condition of an .if/.ifdef/.ifndef statement.

Usage:

.else

Example:

.ifdef SOMETHING
    STA $00
.else
    STA $01
.endif

.endenum

End .enum.

Usage:

.endenum

Example:

.enum $00, 1, OP
OP_YIELD
OP_DRAW
.endenum

.endif

End .if/.ifdef/.ifndef statement.

Usage:

.endif

Example:

.ifdef SOMETHING
    STA $00
.else
    STA $01
.endif

.endm

End .macrodef.

Usage:

.endm

Example:

.macrodef TEST_MACRO
    LDA #\1
    STA <\2
.endm

See the section on Macros for more information.

.endtable

End a .table.

Usage:

.endtable

Example:

.table 2
[0] .dw on_start
[1] .dw on_select
.endtable

.enum

Start a block of sequential constants, closed by .endenum.

Usage:

.enum START[, STEP[, NAME]]
  • START - Number, required. The value of the first member.
  • , STEP - Number, optional (default 1). How far the counter moves for each member. It may be zero or negative.
  • , NAME - Name, optional. Names the enum, which defines NAME_COUNT. A named enum needs STEP written out, even when it is 1.

Each line in the block is one member:

FormValueCounter afterwards
NAMEcountercounter + STEP
NAME .rs Ncountercounter + N × STEP
NAME = exprexprexpr + STEP
NAME\icountercounter + STEP (inside a .for)

The forms can be mixed, and a member line can carry a trailing comment.

A bare member name must start in the first column. As everywhere else, an indented word is an instruction, so NOP inside an .enum still assembles to $EA, and an indented OP_DRAW is reported as an unknown opcode with a hint to move it to the first column. Outside an .enum, a bare name is still a constant equal to 1.

NAME = expr gives that member the value expr and restarts the counter from there, as in C: the next member is expr + STEP.

Example:

.enum $00, 1, OP
OP_YIELD          ; $00
OP_DRAW           ; $01
OP_FRAME          ; $02
OP_SPECIAL = $10  ; $10
OP_AFTER          ; $11
.endenum

    LDA #OP_COUNT ; 5

A named enum defines one constant, NAME_COUNT (the name followed by _COUNT), equal to the number of members. It can be used before the enum, like any constant. The name itself is not a symbol: it cannot be used in an expression, .ifdef OP is false, and a constant called OP can sit alongside .enum $00, 1, OP. Members do not need to share the name as a prefix.

Notes:

  • Members inside a false .if are not defined and not counted, but still move the counter, as .rs always has.
  • An .enum inside another resets the counter, and the first .endenum closes both. When either one is named, nesting is an error.
  • A named .enum without a matching .endenum is an error; defining the same name twice is an error, as is defining one member twice in a named enum.

.error

Fail the build with a message whenever the line is assembled.

Usage:

.error "MESSAGE"
  • "MESSAGE" - String, required. The error to report.

Example:

.if LEVEL_TYPE > 4
    .error "unsupported LEVEL_TYPE"
.endif

Output:

Error in `level.asm` on line 2: unsupported LEVEL_TYPE

.error follows the same rules as .assert: it is checked after the last pass, so the branch it is in is the one that produced the bytes; it is skipped in any false .if branch; and \1/\i in its message are replaced the same way.

.fill

Fill with bytes.

Usage:

.fill COUNT[, VALUE]
  • COUNT - Number, required. Number of bytes to fill.
  • , VALUE - Number, optional. Value of each byte. Defaults to $FF.

Example:

.fill 16

Output:

00000000  ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
00000010

Try it:

.fill 16

The value may be negative: .fill 4, -1 emits four $FF bytes.

00000000  ff ff ff ff                                       |....|
00000004

.font

Generate font character tile.

Usage:

.font START[, END]
  • START - Character/number, required. Starting ASCII character or code.
  • [, END] - Character/number, optional. Ending ASCII character or code. If included, all font tiles from START to [, END] (inclusive) will be generated.

Example:

.font 'A', 'G'

Output:

00000000  38 44 7c 44 44 44 44 00  38 44 7c 44 44 44 44 00  |8D|DDDD.8D|DDDD.|
00000010  78 44 78 44 44 44 78 00  78 44 78 44 44 44 78 00  |xDxDDDx.xDxDDDx.|
00000020  38 44 40 40 40 44 38 00  38 44 40 40 40 44 38 00  |8D@@@D8.8D@@@D8.|
00000030  78 44 44 44 44 44 78 00  78 44 44 44 44 44 78 00  |xDDDDDx.xDDDDDx.|
00000040  7c 40 70 40 40 40 7c 00  7c 40 70 40 40 40 7c 00  ||@p@@@|.|@p@@@|.|
00000050  7c 40 70 40 40 40 40 00  7c 40 70 40 40 40 40 00  ||@p@@@@.|@p@@@@.|
00000060  3c 40 4c 44 44 44 38 00  3c 40 4c 44 44 44 38 00  |<@LDDD8.<@LDDD8.|
00000070

Read more about PPU pattern tables here.

Try it:

.font 'A', 'G'

.hibytes

Output only the high byte of 16-bit word(s).

Usage:

.hibytes NUMBER[, NUMBER]
  • NUMBER - Number, required. At least one number is required.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.hibytes $1234, $5678

Output:

00000000  12 56                                             |.V|
00000002

Try it:

.hibytes $1234, $5678

.if

Test if condition.

Can be accompanied by an .else and must be accompanied by an .endif.

Usage:

.if CONDITION

Example:

.if SOMETHING == $01
    LDA #$01
.endif

.ifdef

Test if variable is defined.

Can be accompanied by an .else and must be accompanied by an .endif.

Usage:

.ifdef VARIABLE
  • VARIABLE - Variable/constant/etc., required. The code that follows will be processed if the variable has been defined.

Example:

.ifdef SOMETHING
    STA $00
.else
    STA $01
.endif

.ifndef

Test if variable has not been defined.

Can be accompanied by an .else and must be accompanied by an .endif.

Usage:

.ifndef VARIABLE
  • VARIABLE - Variable/constant/etc., required. The code that follows will be processed if the variable has not been defined.

Example:

.ifndef SOMETHING
    STA $01
.else
    STA $00
.endif

.incbin

Include binary file.

Usage:

.incbin "FILENAME"[, OFFSET[, LIMIT]]
  • "FILENAME" - Path to file, required. Must be within quotes.
  • [, OFFSET - File offset index, optional. Index at which to start including binary file.
  • [, LIMIT]] - Limit in bytes, optional. Number of total bytes to include.

Example:

.incbin "file.bin"

.include

Include assembly file.

Usage:

.incbin "FILENAME"
  • "FILENAME" - Path to file, required. Must be within quotes.

Example:

.include "file.asm"

Included files share a global state with other included files and the main entry point file. That means if a variable is defined in one file, it is available to all other files, provided that they are included after the definition.

Relative filenames in .include — and in every filename-based directive (.incbin, .incpng, .incpal, .incrle, .incwav, .inestrn) — are resolved relative to the directory of the file that contains the directive. A file included from a subdirectory therefore resolves its own includes and assets from that subdirectory, not from the top-level project directory. A path prefixed @/ is the escape from this: see Project-root-relative paths below.

Declaring a filename argument

Any filename argument may be written with a file:// prefix, which declares that the string names an input file:

.incbin "file://logo.chr"
.include "file://defs.asm"

The prefix is stripped before the path is used, so the two spellings load exactly the same file — file:// adds information about the argument rather than changing it. It is a marker, not a URL scheme: there is no host part and no percent-decoding, and file:///path/to/logo.chr is simply the absolute spelling.

The declaration earns its keep on a custom pseudo-instruction, where the assembler otherwise cannot tell that a string is a path. On the built-in directives above it is accepted, harmless, and redundant — their arguments are already known to be filenames — but it lets you write every path in a project the same way. Editors make a declared path clickable either way.

Project-root-relative paths

A filename argument beginning @/ resolves from the project root instead of the containing file's directory:

.include "@/lib/macros.asm"
.incbin  "@/assets/logo.chr"
.incpng  "@/art/tiles.png"

@/lib/macros.asm names the same file no matter which directory the .include sits in — copying that line into a file three levels deeper still finds it, where a relative path would need ../../../lib/macros.asm at that depth and break the moment the file moves again. Everything after the @/ is a path relative to the root:

ArgumentResolves to
"@/assets/logo.chr"<root>/assets/logo.chr
"@weird/logo.chr"<containing dir>/@weird/logo.chr (unchanged — @ not followed by / is an ordinary path character)
"./@x/logo.chr"<containing dir>/@x/logo.chr (the escape hatch for a directory literally named @)

The project root is found by walking up from the entry file for the nearest .nessemblerc, .nessemblerc.json, or .nessembleignore — the root is the directory containing that marker. A project that already has one of these files gets @/ for free. With no marker anywhere above it, the entry file's own directory is the root, which makes @/foo mean ./foo for a lone source file. The --root CLI flag, and an open editor's workspace folder, both override the walk-up explicitly.

@/ composes with file://: the declaration is stripped first, so "file://@/lib/defs.asm" is a declared, root-relative path — see Declaring a filename argument above and Declaring file arguments for what a custom pseudo-op's script receives.

A @/ path that cannot be resolved is a hard error rather than a silent fallback to file-relative resolution: this happens when no project root can be determined at all (only reachable from the browser playground, which has no filesystem), or when the path climbs back out of the root, e.g. "@/../secret.bin".

.incpal

Include palette from PNG.

Usage:

.incpal "FILENAME"
  • "FILENAME" - Path to file, required. Must be within quotes.

Example:

.incpal "palette.png"

The PNG will be scanned, row-by-row/pixel-by-pixel, from the top-left to the bottom-right until it encounters 4 different, but not necessarily unique, colors.

.incpng

Include PNG.

Converts the PNG to CHR tiles. The image must include only 4 colors:

ColorNameRGBHex
Black0, 0, 0#000000
Dark Grey85, 85, 85#555555
Light Grey170, 170, 170#AAAAAA
White255, 255, 255#FFFFFF

Other colors may be used, but accuracy is not guaranteed.

Usage:

.incpng "FILENAME"
  • "FILENAME" - Path to file, required. Must be within quotes.

Example:

.incpng "image.png"

Read more about PPU pattern tables here.

.incrle

Include binary data to be RLE-encoded

The RLE-encoding scheme used is one featured in a few Konami NES titles, known as Konami RLE. The breakdown of bytes:

ValueDescription
00-80Read another byte and write it to the output N times
81-FECopy N-128 bytes from input to output
FFEnd of compressed data

Usage:

.incrle "FILENAME"
  • "FILENAME" - Path to file, required. Must be within quotes.

Read more about NES RLE compression here.

.incwav

Include WAV.

Converts WAV to a 1-bit PCM.

Usage:

.incwav "FILENAME"[, AMPLITUDE]
  • "FILENAME" - Path to file, required. Must be within quotes.
  • [, AMPLITUDE] - Amplitude, optional. Amplitude of WAV.

Example:

.incwav "audio.wav", 24

.ines2

Emit a NES 2.0 header.

Sets bits 2-3 of Flags 7 to the NES 2.0 identifier (10) and switches the output header from iNES 1.0 to NES 2.0, which widens the mapper (0-4095) and PRG/CHR sizes and repurposes bytes 8-15.

When NES 2.0 mode is active, some existing directives change meaning:

NES 2.0-only directives (.inessubmap, .inesprgnvram, .ineschrram, .ineschrnvram, .inestiming, .inesconsole, .inesvsppu, .inesvshw, .inesmiscrom, .inesexpansion) require this directive.

Usage:

.ines2 FLAG
  • FLAG - Number, required. Non-zero to emit a NES 2.0 header.

Example:

.ines2 1

.ines4scr

iNES four-screen VRAM flag.

Sets bit 3 of Flags 6 (the "alternative nametable layout" bit), used by boards that provide four-screen VRAM instead of the hard-wired mirroring selected by .inesmir.

Usage:

.ines4scr FLAG
  • FLAG - Number, required. Non-zero to set four-screen VRAM.

Example:

.ines4scr 1

.inesbat

iNES battery / persistent memory flag.

Sets bit 1 of Flags 6, indicating the cartridge contains battery-backed PRG-RAM at $6000-$7FFF (or other persistent memory).

Usage:

.inesbat FLAG
  • FLAG - Number, required. Non-zero to indicate persistent memory.

Example:

.inesbat 1

.ineschr

iNES CHR count.

Usage:

.ineschr COUNT
  • COUNT - Number, required. Number of CHR banks. In NES 2.0 mode a count above 255 also writes the byte-9 MSB nibble (up to 4095).

Example:

.ineschr 1

.ineschrnvram

NES 2.0 battery CHR-RAM size.

Sets the battery-backed CHR-RAM field (byte 11 bits 4-7) of a NES 2.0 header. Requires .ines2.

Usage:

.ineschrnvram BYTES
  • BYTES - Number, required. Size in bytes: 0, or a power-of-two byte count from 128 to 2097152 (stored as the shift count size = 64 << n).

Example:

.ineschrnvram 8192

.ineschrram

NES 2.0 CHR-RAM size.

Sets the volatile CHR-RAM field (byte 11 bits 0-3) of a NES 2.0 header. Requires .ines2.

Usage:

.ineschrram BYTES
  • BYTES - Number, required. Size in bytes: 0, or a power-of-two byte count from 128 to 2097152 (stored as the shift count size = 64 << n).

Example:

.ineschrram 8192

.inesconsole

NES 2.0 console type.

Sets bits 0-1 of Flags 7. Requires .ines2. This is the canonical form of .inesvs (value 1) and .inespc10 (value 2); setting a conflicting combination is an error.

ValueConsole type
0Nintendo NES / FC
1VS System
2PlayChoice-10
3Extended (unsupported)

Value 3 (extended console type) is not yet supported.

Usage:

.inesconsole NUMBER
  • NUMBER - Number, required. Console type (0-3).

Example:

.inesconsole 1

.inesexpansion

NES 2.0 default expansion device.

Sets byte 15 (bits 0-5) of a NES 2.0 header. Requires .ines2.

Usage:

.inesexpansion NUMBER
  • NUMBER - Number, required. Expansion device (0-63).

Example:

.inesexpansion 1

.inesmap

iNES mapper number.

Usage:

.inesmap NUMBER
  • NUMBER - Number, required. Mapper number. iNES supports 0-255; in NES 2.0 mode the range widens to 0-4095 (byte 8 holds the high nibble). A value above 255 requires .ines2.

Read more about NES mappers here.

.inesmir

iNES mirroring.

Sets bit 0 of Flags 6, the hard-wired nametable arrangement. The other Flags 6 bits are controlled by their own directives: .inesbat (battery), .inestrn (trainer), and .ines4scr (four-screen VRAM).

xxxxxxx0
       |
       +- Mirroring: 0: horizontal (vertical arrangement)
                     1: vertical (horizontal arrangement)
ValueMirroring
0Horizontal
1Vertical

Usage:

.inesmir NUMBER
  • NUMBER - Number, required. Mirroring type.

.inesmiscrom

NES 2.0 miscellaneous ROM count.

Sets byte 14 (bits 0-1) of a NES 2.0 header, the number of miscellaneous ROMs present. Requires .ines2.

Usage:

.inesmiscrom NUMBER
  • NUMBER - Number, required. Number of miscellaneous ROMs (0-3).

Example:

.inesmiscrom 1

.inespc10

iNES PlayChoice-10 flag.

Sets bit 1 of Flags 7, marking the ROM as a PlayChoice-10 title. This bit is not part of the official specification and most emulators ignore it. In NES 2.0 mode this is sugar for .inesconsole type 2.

Only the header bit is set. The optional 8 KB PlayChoice INST-ROM and PROM data sections are not emitted.

Usage:

.inespc10 FLAG
  • FLAG - Number, required. Non-zero to mark a PlayChoice-10 title.

Example:

.inespc10 1

.inesprg

iNES PRG count.

Usage:

.inesprg COUNT
  • COUNT - Number, required. Number of PRG banks. In NES 2.0 mode a count above 255 also writes the byte-9 MSB nibble (up to 4095).

Example:

.inesprg 1

.inesprgnvram

NES 2.0 battery PRG-RAM size.

Sets the battery-backed PRG-RAM field (byte 10 bits 4-7) of a NES 2.0 header. Requires .ines2.

Usage:

.inesprgnvram BYTES
  • BYTES - Number, required. Size in bytes: 0, or a power-of-two byte count from 128 to 2097152 (stored as the shift count size = 64 << n).

Example:

.inesprgnvram 8192

.inesprgram

iNES / NES 2.0 PRG-RAM size.

In iNES mode, sets byte 8 of the header, the size of PRG-RAM in 8 KB units (a value of 0 infers 8 KB for compatibility).

In NES 2.0 mode, sets the volatile PRG-RAM field (byte 10 bits 0-3) and the argument is a byte size instead — pair it with .inesprgnvram for battery-backed PRG-RAM.

Usage:

.inesprgram SIZE
  • SIZE - Number, required. In iNES mode, PRG-RAM size in 8 KB units. In NES 2.0 mode, a byte size: 0, or a power-of-two byte count from 128 to 2097152 (stored as the shift count size = 64 << n).

Example:

.inesprgram 1

.inessubmap

NES 2.0 submapper number.

Sets byte 8 (bits 4-7) of a NES 2.0 header, the submapper that distinguishes variants of a mapper. Requires .ines2.

Usage:

.inessubmap NUMBER
  • NUMBER - Number, required. Submapper number (0-15).

Example:

.inessubmap 1

.inestiming

NES 2.0 CPU/PPU timing.

Sets byte 12 of a NES 2.0 header, the region timing. Requires .ines2. When unset, .inestv provides the NTSC/PAL value.

ValueTiming
0RP2C02 (NTSC)
1RP2C07 (PAL)
2Multi-region
3UMC 6527P (Dendy)

Usage:

.inestiming NUMBER
  • NUMBER - Number, required. Timing (0-3).

Example:

.inestiming 0

.inestrn

iNES trainer include.

The assembled trainer must be no larger than 512 (0x200) bytes. The appropriate flag is automatically set in the iNES header to indicate a trainer is present.

Usage:

.inestrn "FILENAME"
  • "FILENAME" - Path to file, required. Must be within quotes.

Example:

.inestrn "trainer.asm"

.inestv

iNES TV system.

Sets bit 0 of Flags 9, the TV system the ROM targets. PAL is also mirrored into the unofficial Flags 10 TV-system field (bits 0-1: 0 NTSC, 2 PAL) that some emulators honor. In NES 2.0 mode this instead provides the NTSC/PAL fallback for the .inestiming byte.

xxxxxxx0
       |
       +- TV system: 0: NTSC
                     1: PAL
ValueTV systemFlags 9Flags 10
0NTSC00
1PAL12

Usage:

.inestv SYSTEM
  • SYSTEM - Number, required. 0 for NTSC, 1 for PAL.

Example:

.inestv 1

.inesvs

iNES VS Unisystem flag.

Sets bit 0 of Flags 7, marking the ROM as a VS Unisystem arcade title. In NES 2.0 mode this is sugar for .inesconsole type 1.

Usage:

.inesvs FLAG
  • FLAG - Number, required. Non-zero to mark a VS Unisystem title.

Example:

.inesvs 1

.inesvshw

NES 2.0 VS System hardware type.

Sets byte 13 (bits 4-7) of a NES 2.0 header. Only meaningful when the .inesconsole type is VS (1); ignored otherwise. Requires .ines2.

Usage:

.inesvshw NUMBER
  • NUMBER - Number, required. VS System hardware type (0-15).

Example:

.inesvshw 0

.inesvsppu

NES 2.0 VS System PPU type.

Sets byte 13 (bits 0-3) of a NES 2.0 header. Only meaningful when the .inesconsole type is VS (1); ignored otherwise. Requires .ines2.

Usage:

.inesvsppu NUMBER
  • NUMBER - Number, required. VS System PPU type (0-15).

Example:

.inesvsppu 0

.lobytes

Output only the low byte of 16-bit word(s).

Usage:

.lobytes NUMBER[, NUMBER]
  • NUMBER - Number, required. At least one number is required.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.lobytes $1234, $5678

Output:

00000000  34 78                                             |4x|
00000002

Try it:

.lobytes $1234, $5678

.macro

Call macro.

Usage:

.macro MACRO[, NUMBER, ...]
  • MACRO - Name, required. Name of previously-defined macro.
  • , NUMBER, ... - Number(s), optional. Additional comma-separated numbers may be used.

Example:

.macro TEST_MACRO

See the section on Macros for more information.

.macrodef

Start macro definition.

Usage:

.macrodef MACRO
    CODE...
.endm
  • MACRO - Name, required. Name of macro.
  • CODE... - Code, required. Assembly code.

Example:

.macrodef TEST_MACRO
    LDA #\1
    STA <\2
.endm

See the section on Macros for more information.

.org

Organize code.

Set the address of the current bank in which to start organizing code.

Usage:

.org ADDRESS

Example:

.org $C000

.out

Print a message while assembling.

Usage:

.out "MESSAGE"
  • "MESSAGE" - String, required. The line to print.

The line goes to stderr, never stdout, so a ROM written to stdout is not disturbed. It is printed once per build, after assembly and before any warnings or errors, in the order the lines ran. A .out in a .for body prints once per iteration; one in a false .if branch prints nothing. \1/\i in the message are replaced as in .assert. The language server never shows .out lines.

Example:

.for 0, 1
.out "building bank \i"
.endfor

Output (stderr):

building bank 0
building bank 1

.phase

Assemble code for a different run-time address.

When a PRG bank is swapped in at a different address than the one it is laid out at, the address labels receive (its .org) does not match where the code actually runs. .phase ADDRESS overrides the address labels receive so it reflects the run-time (post-swap) location, while ROM layout keeps flowing from .org unchanged. This removes the need to subtract the swap offset from every label by hand.

The override stays in effect until .dephase or a bank/segment switch (.prg, .chr, .segment). It applies only to symbol values; branch targets and emitted bytes are unaffected, since the offset cancels in any address difference.

Usage:

.phase ADDRESS
  • ADDRESS - Number, required. The run-time address the current location maps to.

Example:

.prg 1
.org $C000       ; laid out at $C000 in ROM
.phase $8000     ; but swapped in at $8000 at run time

label_def:       ; label_def == $8000
    NOP
    JMP label_def

.dephase

.prg

Set PRG bank index.

Usage:

.prg NUMBER
  • NUMBER - Number, required. PRG bank index.

Example:

.prg 0

PRG banks are 4K bytes (0x4000) in size.

.random

Output random byte(s).

The algorithm for the PRNG is the suggested POSIX implementation of rand().

Usage:

.random [SEED[, COUNT]]
  • [SEED - Number or string, optional. Seeds the random number generator. Defaults to the current system time.
  • [, COUNT]] - Number of bytes to output, optional. Defaults to 1.

Example:

.random "Secret Key", 16

.rsset

Set initial value for .rs declarations.

Usage:

.rsset ADDRESS
  • ADDRESS - Number, required. Address to start .rs declarations.

Example:

.rsset $0000

.rs

Reserve space for variable declaration.

Usage:

VARIABLE .rs NUMBER
  • VARIABLE - Variable name, required. Name of variable to declare.
  • NUMBER - Number (in bytes) to reserve, required.

Example:

.rsset $0000

label_01 .rs 1
label_02 .rs 2
label_03 .rs 1

.db label_01, label_02, label_03

Output:

00000000  00 01 03                                          |...|
00000003

Try it:

.rsset $0000

label_01 .rs 1 label_02 .rs 2 label_03 .rs 1

.db label_01, label_02, label_03

.segment

Set code segment.

Usage:

.segment "SEGMENT[0-9]+"
  • SEGMENT - Type of segment, required. PRG or CHR.
  • [0-9]+ - Number, required. Segment index.

The whole segment must be within quotes.

Example:

.segment "PRG1"

This is an alias for .prg x.

.table

Check an indexed table: tag each entry with the key it is looked up by, and the assembler checks that every entry is where its key says, that every entry is the same size and, when told, that the table has exactly the right number of entries. Closed by .endtable.

Usage:

.table [COUNT | ENUM][, FIRST]
    [KEY] statement
    ...
.endtable

Each entry starts with a [KEY] tag, written first on its line. Entry n (counting from 0) must be tagged FIRST + n: .table checks the order, it never reorders. A tag emits nothing, so converting a table whose entries carry ; $NN comments into tags gives byte-identical output, and the build fails as soon as a key and its entry stop lining up.

Example:

.enum $00, 1, OP
OP_YIELD
OP_DRAW
OP_FRAME
.endenum

opcode_table:
    .table OP
    [OP_YIELD]  .dw op_yield
    [OP_DRAW]   .dw op_draw
    [OP_FRAME]  .dw op_frame
    .endtable

op_yield:
    RTS
op_draw:
    RTS
op_frame:
    RTS

Output:

00000000  06 00 07 00 08 00 60 60  60                       |......```|
00000009

Try it (swap two entries to see the error):

.enum $00, 1, OP OP_YIELD OP_DRAW OP_FRAME .endenum

opcode_table: .table OP [OP_YIELD] .dw op_yield [OP_DRAW] .dw op_draw [OP_FRAME] .dw op_frame .endtable

op_yield: RTS op_draw: RTS op_frame: RTS

The arguments choose what is checked:

FormFirst keyEntry count checked
.table0no
.table COUNT0exactly COUNT
.table COUNT, FIRSTFIRSTexactly COUNT
.table ENUMthe enum's first valueone entry per member
.table ENUM, FIRSTFIRSTone entry per member from the one whose value is FIRST on

COUNT is any expression (.table 40, .table OP_COUNT). ENUM is the name of a named .enum: the keys step by the enum's STEP, so an enum with a step of 2 takes the pre-doubled keys of a .dw table indexed with ASL / TAX. A missing member is reported by name. If a name is both a named enum and a constant, the enum wins. A table that starts at 1 states its count (.table 24, 1) or uses its enum; there is no .table , 1.

Keys. A key is any expression: a constant, a number ([$05]), a sum ([OBJ_FIRST + 2]), a loop counter ([\i]) or a symbol defined further down. As everywhere, operators share one precedence level and group from the right, so [KEY*2+1] is KEY*(2+1).

Entries. An entry runs from its tag to the next tag (or .endtable), so one may span several lines; a tag can also stand on a line of its own:

.table 2
[0] .db 1, 2
    .lobytes handler_a
[1]
    .db 3, 4
    .lobytes handler_b
.endtable

A tag can prefix any statement: data, an instruction ([K] JMP [ptr] is a tag and an indirect jump), a .macro call or a custom pseudo-instruction, whose bytes all count toward the entry. Comments, blank lines, labels, constants and anything else that emits nothing may sit anywhere in a table; a label does not start an entry. A tag cannot prefix a label or constant on the same line, .table, .endtable or .macrodef, and a line starts with at most one tag.

Loops and conditionals. A .for inside a table makes one entry per iteration:

.table 8
.for 0, 7
    [\i] .dw row\i
.endfor
.endtable

An .if inside a table can drop entries, and the order check sees only the entries that were assembled. A .table inside a false .if is ignored. A .table must not straddle a .for body or an .if block.

Notes:

  • Bytes inside a table before its first tag are an error, and so is an entry that emits no bytes.
  • .org, .prg, .chr, .segment and .inestrn cannot be used inside a table; .phase and .dephase can.
  • Only the first out-of-place entry is reported (one inserted entry shifts every later one); every wrong-size entry is reported.
  • Tables don't nest, and a custom pseudo-instruction's emitted source cannot contain .table, .endtable or a tag; put the tag on the line that invokes it instead.
  • A table whose last entry is cut short (the next table's first byte doubles as its last byte) fails the size check: end the .table before that entry.

Optional Scripts

Some scripts are included with nessemble, but totally optional. They must be installed with the scripts command which provides additional pseudo-instructions to use.

Pseudo-InstructionDescription
.easeGenerates bytes to simulate easing

.ease

Generates bytes to simulate easing

Usage:

.ease FUNCTION[, START[, END[, STEPS]]]
  • FUNCTION - String, required. Easing function to perform. Must be within quotes.
  • [, START - Number, optional. Starting value. Defaults to 0.
  • [, END - Number, optional. Ending value. Defaults to 16.
  • [, STEPS]]] - Number, optional. Steps to perform. Defaults to 16.

Valid FUNCTIONs include:

  • "easeInQuad"
  • "easeOutQuad"
  • "easeInOutQuad"
  • "easeInCubic"
  • "easeOutCubic"
  • "easeInOutCubic"
  • "easeInQuint"
  • "easeOutQuint"
  • "easeInOutQuint"
  • "easeInBounce"
  • "easeOutBounce"
  • "easeInOutBounce"

Example:

.ease "easeOutBounce", 0, $20, $40

Output:

00000000  00 00 00 00 00 01 02 02  03 04 06 07 08 0a 0b 0d  |................|
00000010  0f 11 13 16 18 1a 1d 1f  1e 1d 1c 1b 1a 19 19 18  |................|
00000020  18 18 18 18 18 18 18 19  19 1a 1b 1c 1d 1e 1f 1f  |................|
00000030  1e 1e 1e 1e 1e 1e 1e 1e  1f 1f 1f 1f 1f 1f 1f 20  |............... |
00000040

Try it — the .ease script runs in your browser (custom pseudo-op scripting, compiled to WebAssembly):

.ease "easeOutBounce", 0, $20, $40

Macros

Macros may be utilized to maximize code-reuse and may also be treated as custom functions.

Example:

.macrodef TEST_MACRO
    LDA #$00
    STA $2005
    STA $2005
.endm

.macro TEST_MACRO

Output:

00000000  a9 00 8d 05 20 8d 05 20                           |.... .. |
00000008

Try it:

.macrodef TEST_MACRO LDA #$00 STA $2005 STA $2005 .endm

.macro TEST_MACRO

Parameters

Macros may also have parameters.

Example:

.macrodef TEST_MACRO
    LDA #\1
    STA \2
    STA \2
.endm

.macro TEST_MACRO, $00, $2005

Output:

.macrodef TEST_MACRO
    LDA #\1
    STA \2
    STA \2
.endm

.macro TEST_MACRO, $00, $2005

One macro may have up to 256 parameters which are denoted with a \ prefix. The first parameter being \1, the next \2, and so on up to \256. All parameters must be numbers (or label variables).

A macro takes as many arguments as the highest parameter its body uses: the TEST_MACRO above uses \1 and \2, so it takes exactly two, and a call passing one or three is an error at the call. A parameter used only inside an .if still counts.

There is also a pseudo-parameter, \#, that returns the number of input parameters. A macro that uses \# handles its own argument count (for optional arguments, test .if \# >= 3), so its calls are never checked.

Example:

.macrodef COUNT_PARAMS
    .db \#
.endm

.macro COUNT_PARAMS, $01, $01, $01

Output:

00000000  03                                                |.|
00000001

There is another pseudo-parameter, \@, that returns a unique number every time the macro is called.

Example:

.macrodef TEST_MACRO
    LDX #$08
label_\@:
    DEX
    BNE label_\@
.endm

.macro TEST_MACRO
.macro TEST_MACRO
.macro TEST_MACRO

Output:

00000000  a2 08 ca d0 fd a2 08 ca  d0 fd a2 08 ca d0 fd     |...............|
0000000f

A \@-uniquified label (such as label_\@ above) is a real label — it lands in the symbol table with a distinct name per invocation. To keep list files (-l) readable, these macro-created labels are omitted from the list by default; pass --mlist to include them.

Loops

.for START, END … .endfor repeats a block of code, unrolled: the body is assembled once for each value of a counter, which is available inside the body as \i. Unrolling costs bytes but saves the counter and the branch of a runtime loop, which matters for time-critical code such as writing to the PPU during vblank.

Example:

PPUDATA = $2007
src_label = $0300

.for 0, 2
    LDA src_label+\i
    STA PPUDATA
.endfor

Output:

00000000  ad 00 03 8d 07 20 ad 01  03 8d 07 20 ad 02 03 8d  |..... ..... ....|
00000010  07 20                                             |. |
00000012

This assembles exactly as if the body had been written out three times, with \i replaced by 0, 1 and 2.

Try it:

PPUDATA = $2007 src_label = $0300

.for 0, 2 LDA src_label+\i STA PPUDATA .endfor

Both bounds are inclusive expressions: .for 0, 2 runs three times. They may use constants and labels defined above the loop (.for 0, TABLE_LEN-1), but not a symbol defined later: the number of iterations decides how many bytes the loop emits, so it has to be known on the first pass. \i can be used anywhere an expression can (LDA #\i*4, .db \i, .if \i == 0). A single loop may run at most 4096 iterations, and a nest of loops at most 65536 in total.

.for and .endfor may be indented. Like every other directive, they are lowercase: .FOR is not recognised.

Counting down

When START is greater than END the counter counts down.

Example:

.for 7, 4
    .db \i
.endfor

Output:

00000000  07 06 05 04                                       |....|
00000004

Nesting

Loops nest. Inside the innermost loop \i is its own counter, \j is the counter of the loop around it, and \k the one around that.

Example:

PPUDATA = $2007
tiles = $0400

.for 0, 1
    .for 0, 2
        LDA tiles+(\j*8)+\i
        STA PPUDATA
    .endfor
.endfor

Output:

00000000  ad 00 04 8d 07 20 ad 01  04 8d 07 20 ad 02 04 8d  |..... ..... ....|
00000010  07 20 ad 08 04 8d 07 20  ad 09 04 8d 07 20 ad 0a  |. ..... ..... ..|
00000020  04 8d 07 20                                       |... |
00000024

The assembler evaluates expressions strictly right to left with no operator precedence (see Evaluation order), so the outer counter is parenthesised: (\j*8)+\i.

Using \j or \k without that many enclosing loops, or \i outside any loop, is an error.

Labels in a body

An anonymous label and the branches to it work unchanged inside a body, since each reference resolves to the nearest definition.

Example:

.for 0, 1
    LDA $2002
    BPL :+
    NOP
:
    STA $2005
.endfor

Output:

00000000  ad 02 20 10 01 ea 8d 05  20 ad 02 20 10 01 ea 8d  |.. ..... .. ....|
00000010  05 20                                             |. |
00000012

A named label in a body would be defined once per iteration, with every reference quietly resolving to the last copy, so it is an error. Paste the counter onto the name instead.

Pasted names

A name written directly before a counter has the counter's value (in decimal) pasted onto the end, so a body can define one label or constant per iteration: row\i: defines row0, row1 and row2. The same works for a constant (slot\i = \i*4) and for a reference (.dw row\i). Once defined, the pasted names are ordinary symbols that can be used anywhere after (or before) the loop.

Example:

    JSR row1
    RTS

jump_table:
.for 0, 2
    .dw row\i
.endfor

.for 0, 2
row\i:
    LDA #\i
    RTS
.endfor

Output:

00000000  20 0d 00 60 0a 00 0d 00  10 00 a9 00 60 a9 01 60  | ..`........`..`|
00000010  a9 02 60                                          |..`|
00000013

A name may paste only one counter, as its suffix (cell\j\i and row\i_end are errors), the counter must not be negative, and a pasted name that is already defined is an error. Like the labels of a macro, pasted symbols are omitted from the list file (-l) unless --mlist is given.

Macros, includes and errors

A .macro invocation or .include in a body is expanded once and then runs on every iteration, and \i may be passed as a macro argument (.macro SET_PPU, \i). Inside a macro body \i refers to whichever loop the macro is invoked in, so a macro can define a pasted label (entry\i:). A .macrodef in a body is an error, and a conditional (.if … .endif) opened in a body must be closed in it.

An error on a body line is reported once rather than once per iteration, with the first failing counter value added to the message, for example Branch address out of range (in .foriteration\i = 5).