Metadata-Version: 2.4
Name: nopa
Version: 0.1.0
Summary: a 6502/Python hybrid cross assembler for Commodore computers
Author-email: Morten Perriard <morten@perriard.dk>
License-Expression: MIT
Project-URL: Homepage, https://github.com/Morty40/NopAssembler
Project-URL: Source, https://github.com/Morty40/NopAssembler
Project-URL: Issues, https://github.com/Morty40/NopAssembler/issues
Project-URL: Changelog, https://github.com/Morty40/NopAssembler/blob/main/CHANGELOG.md
Keywords: 6502,6510,commodore,c64,commodore 64,c128,c16,plus4,vic20,assembler,cross assembler,disassembler,retro computing
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Assembly
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Assemblers
Classifier: Topic :: Software Development :: Disassemblers
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Dynamic: license-file

# Nop Assembler
a 6502/Python hybrid cross assembler for Commodore computers

[![PyPI](https://img.shields.io/pypi/v/nopa)](https://pypi.org/project/nopa/) [![Python](https://img.shields.io/pypi/pyversions/nopa)](https://pypi.org/project/nopa/) [![Tests](https://github.com/Morty40/NopAssembler/actions/workflows/test.yml/badge.svg)](https://github.com/Morty40/NopAssembler/actions/workflows/test.yml) [![License](https://img.shields.io/github/license/Morty40/NopAssembler)](https://github.com/Morty40/NopAssembler/blob/main/LICENSE.txt)

Nop Assembler is a multi-pass 6502 assembler for Commodore computers: the C64, C128, C16, Plus/4 and VIC-20. Every expression is a Python expression, and assembly code can be generated by Python functions, so the full power of Python is available while writing 6502 code.

- the 6502 instruction set, with the stable illegal instructions and automatic zero page addressing
- the 65C02, Rockwell R65C02 and WDC W65C02 instruction sets
- Python expressions, f-strings and lambdas in operands and directives, and blocks of Python code
- generators: Python functions that return assembly code
- local labels, constants, and zero page variables with `zp()`
- `.repeat`, `.for` and `.if` blocks, and `.optional` code that is only assembled when it is used
- named sections, to store code and data in separate areas of memory
- PETSCII and screen code text encodings, and your own encoding tables
- import of source and Python files, also into a namespace, such as `spr.draw` or `util.double()`, of binary files, and of SID music on the C64
- built-in symbols for each machine with `-t`, such as its hardware registers and KERNAL and BASIC routines, and BASIC lines with their keywords as tokens
- `.assert`, `.print`, `.warning` and `.error`, to check and report while assembling
- a labels file, and VICE monitor commands with labels and breakpoints
- a disassembler, which turns any program into source that assembles to the same bytes, with a monitor view of every instruction
- outputs a `.prg` file, ready to load in an emulator or on a real machine, or a binary file


## Installation

Nop Assembler requires Python 3.11 or later. The easiest way to install it is with [pipx](https://pipx.pypa.io), which installs the `nopa` command in an environment of its own, apart from other Python packages.

### From PyPI

```bash
pipx install nopa
```

To update to the latest release, and to remove it:

```bash
pipx upgrade nopa
```

```bash
pipx uninstall nopa
```

With [uv](https://docs.astral.sh/uv/), `uv tool install nopa` does the same. To use Nop Assembler as a Python library, e.g. for [testing 6502 code](https://github.com/Morty40/NopAssembler#testing-6502-code), install it with `pip install nopa` in a virtual environment.

### From GitHub

The latest source from the repository, including changes that aren't released yet:

```bash
pipx install git+https://github.com/Morty40/NopAssembler.git
```

To update it, run the same command with `--force`. `pipx upgrade` doesn't pick up new commits, as it only reinstalls when the version number changes:

```bash
pipx install --force git+https://github.com/Morty40/NopAssembler.git
```


## Usage

```
nopa <asmFile> -o <outFile> [--format prg|bin] [-t c128|c16|c64|cx16|plus4|vic20] [--cpu 6502|65C02|R65C02|W65C02] [-D <name>[=<value>]] [-l <labelsFile>] [--vice <viceFile>]
nopa -d <binFile> [-o <asmFile>] [--cpu 6502|65C02|R65C02|W65C02] [-l <labelsFile>]
nopa --version
```

| Option | Description |
|---|---|
| `<asmFile>` | the source file to assemble |
| `-d`, `--disassemble <binFile>` | disassemble the `.prg` or binary file instead, see [Disassembling](https://github.com/Morty40/NopAssembler#disassembling) |
| `-o`, `--output <outFile>` | the file to write. Without `-o` the source is assembled and checked, but nothing is saved. When disassembling, the source file to write. Without `-o` the source is printed |
| `--format <prg\|bin>` | the format of the file to write: `prg` (the default), with the load address, or `bin`, only the bytes. The extension of the file name doesn't matter |
| `-t`, `--target <c128\|c16\|c64\|cx16\|plus4\|vic20>` | the target machine, whose [symbols and generators](https://github.com/Morty40/NopAssembler#built-in-symbols) are imported. Without it, only the generic 6502 ones are. `cx16`, for the Commander X16, is experimental |
| `--cpu <6502\|65C02\|R65C02\|W65C02>` | the [cpu](https://github.com/Morty40/NopAssembler#cpu), and so the instructions: `6502` (the default), `65C02`, `R65C02` or `W65C02`. When assembling, `.cpu` can change it |
| `-D`, `--define <name>[=<value>]` | assign a symbol before the source, as `name = value`, or `name = True` without a value. Upper case names are [constants](https://github.com/Morty40/NopAssembler#constants), so the source can't change them, and lower case names are variables. The name can't start with `_`, or be a Python keyword or built-in, such as `len`, or a mnemonic. Can be given more than once |
| `-l`, `--labels <labelsFile>` | the [labels](https://github.com/Morty40/NopAssembler#labels-file) file to write, as Python assignments. When disassembling, the labels file to read |
| `--vice <viceFile>` | the [VICE monitor commands](https://github.com/Morty40/NopAssembler#vice-monitor-commands) file to write: labels and breakpoints |
| `-h`, `--help` | print the usage |
| `--version` | print the version |

For example, `nopa game.asm -t c64 -D NTSC -D 'START=$c000' -o game.prg` defines `NTSC` as `True` and `START` as `$c000`. The value is an expression, as in an assignment. Put it in single quotes when it has a `$` or spaces, so the shell keeps it as it is.

The output file is only written when there are no errors. Errors and warnings are printed to stderr with file name and line number, and the exit code is 1 on errors. After a successful assembly, Nop Assembler prints the memory range used, the range of each [section](https://github.com/Morty40/NopAssembler#section), and a map of the 256 memory pages.

The `.prg` file starts with the 2-byte load address (the lowest address used), followed by every byte up to the highest address used. Gaps are filled with zeros. A `bin` file is the same, without the load address.

A Makefile rule for building `.prg` files for the C64, with its built-in symbols and generators such as `@basicStart()`:

```make
%.prg: %.asm
	nopa $< -t c64 -o $@
```


### Disk, tape and cartridge images

Nop Assembler writes `.prg` and binary files. Disk, tape and cartridge images are a separate build step after assembling, done by tools made for it, such as `c1541` for disk images and `cartconv` for cartridges, both part of [VICE](https://vice-emu.sourceforge.io).

A Makefile that assembles a program and puts it on a `.d64` disk image:

```make
%.prg: %.asm
	nopa $< -t c64 -o $@

game.d64: game.prg
	c1541 -format "game,01" d64 $@ -write $< game
```

`-format` creates the image with the disk name `game` and the id `01`, and `-write` copies the program onto it as `game`. `make game.d64` builds both, and `x64sc -autostart game.d64` loads and runs it in VICE.


### Labels file

`-l` writes the labels to a file, as Python assignments sorted by address:

```python
start = 0x080d
start_loop = 0x083b
irq = 0x0841
```

The labels are named as in the [VICE monitor commands](https://github.com/Morty40/NopAssembler#vice-monitor-commands), and other symbols, such as `VALUE = 5`, are not included. Another source can use the labels with `.import "game.py"`, and Python scripts with `from game import irq`.

### VICE monitor commands

`--vice` writes a file of commands for the VICE monitor: a label for every label in the source, so the monitor shows and accepts label names instead of addresses, and a breakpoint for every [.break](https://github.com/Morty40/NopAssembler#break):

```
al C:080d .start
al C:083b .start_loop
al C:0841 .irq
break C:0841 if RL > $40
```

The labels are sorted by address. A local label is named after its global label, e.g. `_loop` after `start:` is `start_loop`, and a label in a [namespace](https://github.com/Morty40/NopAssembler#import) by its full name with `_` for `.`, e.g. `spr_draw` for `spr.draw`. A local label in generated code is named after the generator and how many times it was called, e.g. `_loop` in the second `@wait()` is `wait2_loop`. Other symbols, such as `VALUE = 5` and zero page variables, are not included. Run the file when starting VICE, or in the monitor with `pb "game.vmc"`:

```
x64sc -moncommands game.vmc game.prg
```


### Disassembling

`nopa -d game.prg -o game.asm` turns a program back into source, which assembles to exactly the same `.prg` file. A `.prg` file starts with its load address, and any other file is loaded at `$1000`.

- Code is found by trying each byte as the start of some code, following branches, `jmp` and `jsr`. It is only code if every path ends with `jmp`, `rts` or `rti`, or on the 65C02s `bra` or `stp`, before it runs into an unknown opcode, `brk`, the middle of another instruction, or the end. Nothing is assumed about BASIC lines.
- Branch, `jmp` and `jsr` destinations get labels like `l1000`. Labels are alone on their line.
- With `-l game.py`, the names from a [labels file](https://github.com/Morty40/NopAssembler#labels-file) are used instead, for the operands and as labels, also in the data: `jsr irq`, `lda sinTable,x`. A name the code uses for an address outside the program, such as a zero page address in a labels file of your own, is assigned at the top: `frame = $02`. The labels file that assembling writes doesn't have the zero page variables, so with it their addresses show as numbers: `inc $02`. Local labels keep their `global_local` names.
- Bytes the code doesn't reach are written as `.byte`, and 16 or more of the same byte as `.bytefill`. Code that is only reached through jump tables or self-modifying code becomes data too.
- With `--cpu 65C02`, `R65C02` or `W65C02`, that cpu's instructions are disassembled too, and the source starts with `.cpu CPU_65C02`, `CPU_R65C02` or `CPU_W65C02`, so it assembles to the same bytes.
- An absolute address below `$100`, e.g. `lda $0010` as `ad 10 00`, is written as `.byte`, as Nop Assembler assembles it with zero page addressing.
- Each instruction ends with a comment showing the instruction as a machine code monitor does, with its address, bytes, the operand as a number, and its cycles: `sta border ; 1000  8D 20 D0  STA $D020       4`. A `*` in the cycles is a cycle that may be added, when indexing crosses a page, or a branch is taken or goes to another page. The comments are aligned, as a second column.

#### Uses

The disassembler reads any program as source, your own or someone else's, with a monitor view of every instruction beside it. The output is always source that Nop Assembler assembles to the same bytes, so it is a starting point for further work, not just something to read.

**Listing your own program.** Assemble with a labels file, and disassemble with the same file, to see the program exactly as it was assembled: generators and blocks such as `.repeat`, `.for` and `.if` expanded, your label names, and the address, bytes and cycles of each instruction:

```bash
nopa game.asm -o game.prg -l game.py
```

```bash
nopa -d game.prg -l game.py
```

For example, this source:
```
start:      ldx #8
_loop:      inc BORDER
            @nop(2)
            dex
            bne _loop
            rts

BORDER = $d020
```
is listed as:
```
; disassembled by Nop Assembler

            .org $1000

start:
            ldx #$08       ; 1000  A2 08     LDX #$08        2
start_loop:
            inc $d020      ; 1002  EE 20 D0  INC $D020       6
            nop            ; 1005  EA        NOP             2
            nop            ; 1006  EA        NOP             2
            dex            ; 1007  CA        DEX             2
            bne start_loop ; 1008  D0 F8     BNE $1002       2**
            rts            ; 100A  60        RTS             6
```

The listing shows the program as the machine sees it: labels keep their names, and symbols from assignments, such as `BORDER`, show as their values, here `$d020`.

**Debugging in VICE.** The addresses are the ones the VICE monitor shows, so a listing next to the emulator tells you which part of your code you are looking at. With `--vice`, the monitor uses the same label names:

```bash
nopa game.asm -o game.prg -l game.py --vice game.vmc
```

```bash
nopa -d game.prg -l game.py -o game.lst
```

```bash
x64sc -moncommands game.vmc game.prg
```

The listing also shows what the assembler chose for you, such as zero page or absolute addressing, and makes self-modifying code easy to follow, as the address column shows which instruction a store writes into.

**Reverse engineering.** Disassemble a program you don't have the source for. Branch, `jmp` and `jsr` destinations get labels such as `l08ec` to start with. As you find out what the code does, name the addresses in a labels file of your own, and disassemble again:

```python
frame = 0x0002
irq = 0x08c3
drawFrame = 0x08ec
```

```bash
nopa -d game.prg -l names.py -o game.asm
```

Each round gives more readable source, and as it assembles to the same program, you can change it and assemble it again, e.g. to fix or extend the program.


### From Python

The `nopa` package has the same two functions as the command line:

```python
import nopa

context = nopa.assembleFile('game.asm', target='c64')
for message in context.warnings + context.errors:
    print(message)

source = nopa.disassembleFile('game.prg')
```

`assembleFile(inFile, target=None, cpu=CPU_6502, defines=None)` assembles `inFile` for the target (`'c128'`, `'c16'`, `'c64'`, `'plus4'`, `'vic20'`, the experimental `'cx16'`, or none) and the cpu (`nopa.cpu.CPU_6502`, `CPU_65C02`, `CPU_R65C02` or `CPU_W65C02`), and returns the `Context` of the last pass. The defines are assigned before the source, as with `-D`: names and expressions, e.g. `{'NTSC': 'True', 'START': '$c000'}`. Nothing is saved: writing files is up to the caller. Its `memory` is a dict of address to byte, `symbols` has the labels and other symbols, `printed` the `.print` output, and `warnings` and `errors` the messages.

`disassembleFile(inFile, labelsFile=None, cpu=CPU_6502)` returns the source.

Both raise `OSError` if a file can't be read, and `assembleFile` raises `ValueError` for an unknown target. Errors in the source don't raise, they are returned in `context.errors`.


### Testing 6502 code

As Nop Assembler is a Python library, your 6502 routines can have unit tests, run in the [py65](https://github.com/mnaberez/py65) 6502 emulator. A test assembles the source, loads it into the emulator, calls a routine, and checks the registers, the memory, and the cycles it took. Python itself is the reference to compare with, so a routine can be tested with every input.

The tests need py65, and Nop Assembler as a library, e.g. in a virtual environment:

```bash
python3 -m venv .venv
```

```bash
.venv/bin/pip install py65 nopa
```

Two routines to test:

```
; routines.asm - two small routines, tested by test_routines.py

temp = zp(1)

; A = A * 10, for A from 0 to 25
mul10:      sta temp
            asl                 ; A * 2
            asl                 ; A * 4
            clc
            adc temp            ; A * 5
            asl                 ; A * 10
            rts

; X = the number of 1 bits in A
countBits:  ldx #0
_loop:      lsr
            bcc _zero
            inx
_zero:      cmp #0
            bne _loop
            rts
```

And their tests:

```python
"""Tests of routines.asm, run in the py65 6502 emulator."""

import unittest

import nopa
from py65.devices.mpu6502 import MPU


class Program:
    """An assembled program, loaded into a 6502 emulator."""

    def __init__(self, asmFile):
        context = nopa.assembleFile(asmFile)
        assert not context.errors, context.errors
        self.labels = context.symbols
        self.cpu = MPU()
        for address, value in context.memory.items():
            self.cpu.memory[address] = value

    def call(self, label, a=0, x=0, y=0):
        """Run the routine with jsr, and return the cycles it took, including the jsr."""
        address = self.labels[label]
        self.cpu.memory[0x0200:0x0203] = [0x20, address & 0xff, address >> 8] # jsr label
        self.cpu.pc, self.cpu.sp = 0x0200, 0xff
        self.cpu.a, self.cpu.x, self.cpu.y = a, x, y
        start = self.cpu.processorCycles
        while self.cpu.pc != 0x0203: # back after the jsr
            self.cpu.step()
        return self.cpu.processorCycles - start


class TestRoutines(unittest.TestCase):

    def setUp(self):
        self.program = Program('routines.asm')

    def testMul10(self):
        """Every input gives the same result as Python."""
        for a in range(26):
            with self.subTest(a=a):
                self.program.call('mul10', a=a)
                self.assertEqual(self.program.cpu.a, a * 10)

    def testCountBits(self):
        """All 256 values, each within a budget of 110 cycles."""
        for a in range(256):
            with self.subTest(a=a):
                cycles = self.program.call('countBits', a=a)
                self.assertEqual(self.program.cpu.x, bin(a).count('1'))
                self.assertLessEqual(cycles, 110)


if __name__ == '__main__':
    unittest.main()
```

```bash
.venv/bin/python -m unittest -v test_routines
```

Each test shows a different idea:

- `testMul10` compares every input with the same calculation in Python.
- `testCountBits` tries all 256 values, and keeps the routine within a cycle budget, which is often what matters most in a demo or a game.

The same approach scales to larger code, e.g. comparing a line drawing routine with a Python version of the algorithm for thousands of random lines.


## Example

```
; hello.asm - prints a message, makes the border red, and returns to BASIC

            @basicStart()
            @basicLine(10, "SYS {start}")    ; 10 SYS 2062
            @basicEnd()

start:      ldx #0
_loop:      lda message,x
            beq _done
            sta $0400,x             ; screen memory
            inx
            bne _loop
_done:      lda #2                  ; red
            sta VIC_BORDER_COLOR
            rts

            .encoding ENCODING_SCREEN_UPPER
message:    .string "HELLO WORLD"
```

```bash
nopa hello.asm -t c64 -o hello.prg
```

Load `hello.prg` in an emulator such as [VICE](https://vice-emu.sourceforge.io), and type `RUN`.


## Syntax

### Lines and comments

Each line holds one statement: an instruction, a directive, an assignment or a generator, optionally preceded by a label. Comments start with `;` and run to the end of the line. Indentation is free.

```
label:      lda #1          ; comment
            .byte 1, 2, 3
value = 42
            @nop(3)
```

### Instructions

All 56 documented 6502 instructions are supported. Mnemonics are written in lowercase.

| Address mode | Syntax |
|---|---|
| implied | `rts` |
| accumulator | `asl` (no operand) |
| immediate | `lda #value` |
| zero page / absolute | `lda address` |
| zero page,x / absolute,x | `lda address,x` |
| zero page,y / absolute,y | `ldx address,y` |
| indirect | `jmp (address)` |
| indexed indirect | `lda (address,x)` |
| indirect indexed | `lda (address),y` |
| relative | `bne label` |

The zero page form is chosen automatically when the address is below `$100` and the instruction has a zero page form. A branch to a destination out of range is an error, and `jmp (address)` with the address on a page boundary (`$xxff`) gives a warning, as the 6502 does not cross the page. The 65C02 does, so there is no warning with `.cpu CPU_65C02`.

The accumulator mode of `asl`, `lsr`, `rol` and `ror` is written without an operand. The `asl a` syntax of some other assemblers is not supported: the operand `a` is an expression like any other, so `asl a` uses a symbol named `a` as a zero page or absolute address.

#### Illegal instructions

The 6510 also runs the "illegal" opcodes of the NMOS 6502, see the [6502 instruction set](https://www.masswerk.at/6502/6502_instruction_set.html). Nop Assembler assembles and disassembles the ones that work the same on all C64 and C128 cpus: `alr`, `anc`, `arr`, `dcp`, `isc`, `las`, `lax`, `rla`, `rra`, `sax`, `sbx`, `slo` and `sre`. As they are instructions, these names can't be used as labels or symbols.

Left out are `anc` `$2b` and `usbc` `$eb`, which do the same as `anc` `$0b` and `sbc #`, and the illegal nops, which would conflict with `nop`. Also left out are the unstable ones, `ane`, `lxa`, `sha`, `shx`, `shy` and `tas`, as they depend on the cpu, its temperature, or the vic. If you need one anyway, store its bytes with `.byte`, or write a generator for it. When disassembling they are data.

### Numbers

| Format | Example |
|---|---|
| decimal | `255` |
| hexadecimal | `$ff` or `0xff` |
| binary | `%11111111` or `0b11111111` |

`%` is also the Python modulo operator. Directly after a number, a name or a `)`, it is modulo: `7 % 4`, `x %10`. Elsewhere, `%` followed by binary digits is a binary number: `lda #%1010`.

### Labels

A label is a name followed by `:`, and gets the value of the current address. A label can be on a line of its own, or in front of a statement. Each label can only be defined once.

```
start:      lda #0
loop:
            jmp loop
```

Labels starting with `_` are local. A local label belongs to the global label before it, so the same local name can be reused under different global labels:

```
clear:      ldx #0
_loop:      sta $0400,x
            inx
            bne _loop       ; clear's _loop
            rts

fill:       ldx #0
_loop:      sta $d800,x
            inx
            bne _loop       ; fill's _loop
            rts
```

From anywhere else, a local label is used by its full name, the global label and the local name: `jmp clear_loop`. Its scope runs to the next global label in the same file, so an `.import` or a generator in between doesn't end it.

The symbol `_` on its own is the current address. Assigning to it moves the current address, like `.org`:

```
            .word _ + 2     ; the address after this word
            _ = $2000       ; same as .org $2000
```

In Python, `_` is the usual name for a value that isn't used, as in `for _ in range(8)`. In Nop Assembler, `_` is the current address in Python code too, so Python code that assigns `_` moves the current address, whether that is meant or not:

- a `.for` loop with `_` in its target, such as `.for _ in range(8)` or `.for _, color in palette`
- a `for` loop or an assignment in a `.python` block, or at the top level of a `.py` file imported without a namespace, such as `for _ in range(8):` or `row, _ = divmod(n, 40)`

There, use another name, such as `i` or `unused`, and `.repeat 8` for lines that only repeat. `_` is fine where Python makes it a local name: in a function, such as a generator, in a lambda or a list comprehension, and in a `.py` file imported into a namespace, which has names of its own.

The current address must be an `int`. Anything else that Python code assigns, such as a float, is an error where the address is next used, and the address becomes 0. In Python, `/` always gives a float, even for `0x4000 / 2`, so divide with `//` instead: `_ = base // 2`.

#### Label names

A global label starts with a letter, and a local label with `_`. After that come letters, digits and underscores: `drawSprite`, `level2`, `player_x`, `_loop`, `_0`. Names are case sensitive, so `Loop` and `loop` are two labels. Capitals are fine as long as the name has a lower case letter too: `Level1`, `screenX`, `_Loop`.

These can't be used:

| Not allowed | Example | Why |
|---|---|---|
| All capitals | `VIC:`, `TABLE2:`, `_LOOP:` | Names in all capitals are for [constants](https://github.com/Morty40/NopAssembler#constants). A label could otherwise replace a built-in constant such as `VIC_BORDER_COLOR` without any warning, and new built-in constants can never clash with your labels |
| A local label before any global label | `_x:` first in a file | It has no global label to belong to. Each file needs its own, as the scope doesn't carry over from the importing file |
| The same name twice | `a:` and `a:` again, or `clear_loop:` after `clear:` and `_loop:` | A label has one address, and a local label's full name counts too |
| A local label in a loop that runs more than once | `.repeat 2` around `_x:` | Each round defines the same name again. Put the code in a [generator](https://github.com/Morty40/NopAssembler#generators) and call it in the loop, as each call has its own scope |
| A built-in function or math name, or a namespace | `lo:`, `ldax:`, `sin:`, `pi:`, or `util:` with `.import "util.py", "util"` | These are symbols too, and a symbol can't change type |
| Other characters | `a.b:`, `a-b:` | `.` and `-` are operators in expressions |
| Two labels on one line | `a: b: nop` | A line has at most one label. Put them on separate lines to give an address two names |
| A Python keyword, or a digit first | `if:`, `class:`, `1a:` | Expressions are Python, so using the name is an error |

The name `a` is best avoided for a label: `asl a` would use the label instead of the accumulator, see [Instructions](https://github.com/Morty40/NopAssembler#instructions). A local label can use any name that isn't all capitals, also `_if` or `_lda`, as its full name is what expressions see.

### Assignments

`name = expression` assigns the value of a Python expression to a symbol. Any Python value can be assigned, not only numbers.

```
SCREEN = $0400
colors = [0, 11, 12, 15, 1]
squares = [x * x for x in range(16)]
            .byte colors[2], squares[3]
```

#### Constants

Symbols in all upper case, such as `SCREEN` or `MAX_SPEED`, are constants: once a constant has a value, it can't be assigned a different value. Doing so is an error, and the constant keeps its first value. Symbols with any lower case letters, such as `speed` or `maxSpeed`, are variables, and can be assigned again, with a value of the same [type](https://github.com/Morty40/NopAssembler#symbol-types).

```
MAX_SPEED = 4
MAX_SPEED = 4               ; ok, the same value
MAX_SPEED = 5               ; error: Constant "MAX_SPEED" cannot be changed from 4 to 5
speed = 1
speed = 2                   ; ok, a variable
```

The built-in symbols, such as `VIC_BORDER_COLOR`, are constants too, so they cannot be given a different value by mistake.

The assembler checks the names it assigns itself: assignments such as `MAX = 5`, labels and `-D` defines. Names that Python assigns are not checked, such as a `.for` target, `:=` in an expression, or code in `.python` and `.py` files, so these can change a constant without an error.

Use a variable for a value that changes, for example in each round of a `.for` loop. Also use a variable for a value calculated from labels that come later in the source, such as `codeSize = end - start`, or from `zp()`, such as `pointer = zp(2)`: while the assembler passes settle, such a value can change, which is an error for a constant.

#### Symbol types

A symbol keeps the type of its first value: an `int` can't become a `str`, a function can't become an `int`, and so on. Assigning a value of another type is an error, and the symbol keeps its old value. This applies to assignments, labels and namespaces. Symbols set by `.for`, like other Python code, are not checked.

```
count = 1
count = 2                   ; ok, still an int
count = "two"               ; error: Symbol "count" cannot change type from int to str
```

This also protects the symbols from Python's `math` module, so a label or assignment can't replace `e`, `pi` or `sin` by mistake:

```
pi = 3                      ; error: Symbol "pi" cannot change type from float to int
sin:        nop             ; error: Symbol "sin" cannot change type from builtin_function_or_method to int
```

Note that `int`, `float` and `bool` are different types. To keep a value that can have decimals, start it as a `float`, e.g. `speed = 1.0`, rather than `speed = 1`.

Symbols set by Python code, with `.python`, or `.import` of a `.py` file without a namespace, are not checked.

#### Zero page variables

`zp(size)` allocates `size` bytes in zero page, and returns the address of the first. Assign it to a name to make a zero page variable:

```
count = zp(1)                   ; $02
pointer = zp(2)                 ; $03 and $04, e.g. for (pointer),y
buffer = zp(8)                  ; $05 to $0c
            lda count
            sta (pointer),y
```

Addresses are allocated from `$02` and up, as `$00` and `$01` are used by the CPU port, in the order the source assigns them. A zero page variable is an ordinary symbol, so it can be used before its assignment. It isn't a label, so it isn't in the labels file or the VICE monitor commands. Allocating more than the 254 bytes from `$02` to `$ff` is an error.

Each call of `zp()` allocates new bytes, also when its address is assigned to a name that already has zero page, and in each round of a `.repeat` or `.for`. The name then holds the address from its latest assignment, and a use before its first assignment gets the last one. So give each zero page variable a name of its own, assigned once, and use one call for a block of bytes, such as `zp(8)`.

### Expressions

Operands and directive arguments are Python expressions, evaluated with all symbols (labels and assignments) as variables. Symbols can be used before they are defined, as Nop Assembler assembles in multiple passes.

```
            lda #lo(message)
            ldx #hi(message)
            .byte 1 if DEBUG else 0
            .byte len(squares), max(squares)
```

The arguments of a directive are those of a Python call, without the parentheses. So a list, a tuple or another iterable can be unpacked into arguments with `*`, and an argument can be given by the name in the directive's syntax, such as `offset` in `.binary "filename"[, offset[, length]]`:

```
squares = [x * x for x in range(16)]
            .byte *squares                  ; the 16 squares
            .byte 0, *squares[1:4], 255     ; 00 01 04 09 ff
            .binary "music.sid", offset=$7e ; without the header of the SID file
```

As in Python, a tuple without `*` is one argument, so `.byte point` with `point = (24, 50)` is an error, and `.byte *point` stores 24 and 50.

Besides the Python built-ins, these are available:

| Symbol | Description |
|---|---|
| `_` | the current address |
| `lo(x)`, `hi(x)` | the low and high byte of a 16-bit value |
| `ord(char)`, `chr(value)` | convert between a character and its value, in the current text encoding |
| `zp(size)` | allocate zero page bytes, see [zero page variables](https://github.com/Morty40/NopAssembler#zero-page-variables) |
| `ref("label")` | true if the label was referenced in the last pass, see below |
| `has("instruction")` | true if the instruction would assemble on the current cpu, see [.if](https://github.com/Morty40/NopAssembler#if-elif-else-end) |
| `sin`, `cos`, `pi`, `floor`, ... | everything from Python's `math` module, protected by the [symbol types](https://github.com/Morty40/NopAssembler#symbol-types) |
| `ENCODING_...` | the text encodings, see `.encoding` |
| `CPU_6502`, `CPU_65C02`, `CPU_R65C02`, `CPU_W65C02` | the cpus, see `.cpu` |

Nop Assembler prefers readable names to symbols, so the low and high byte are `lo(x)` and `hi(x)`, instead of the `<x` and `>x` of other assemblers.

Strings in double quotes are Python f-strings, so `{expression}` inside a string is replaced with its value:

```
version = 2
            .text "VERSION {version}"
```

### Generators

In Nop Assembler, macros are replaced by generators, which are much stronger: a generator is an ordinary Python function, with the full Python language and its libraries available to it.

A line starting with `@` is a generator: a Python expression that returns assembly source code as a string. The code is assembled in place of the generator line. Generators are Python functions, typically defined in a Python file and imported with `.import`, also into a [namespace](https://github.com/Morty40/NopAssembler#import) of their own: `@util.delay(100)`.

```python
# macros.py
def delay(n):
    return f"""
        ldx #{n}
_loop:  dex
        bne _loop
    """
```

```
            .import "macros.py"
            @delay(100)
            @delay(200)
```

Local labels in the generated code get their own scope for each call, so a generator can be used any number of times. Generator arguments can be any Python expression, including labels and keyword arguments: `@jump(address=start)`.

As a generator is Python, it can read files, and use loops, conditions and data structures to decide what code or data to produce. This one turns a level drawn in a text file into tile numbers, with the characters and their tiles given as a dictionary:

```python
# level.py
import os

def tileMap(filename, tiles):
    with open(os.path.join(SOURCE_FOLDER, filename)) as f:
        rows = f.read().splitlines()
    return '\n'.join('.byte ' + ', '.join(str(tiles[char]) for char in row) for row in rows)
```

```
            .import "level.py"
level:      @tileMap("level1.txt", {'.': 0, '#': 1, '*': 2})
```

A generator can also write the code itself, working out the best code for its arguments. This one writes speedcode that draws characters on the screen, without a loop. It groups the positions by character, so each character needs only one `lda`, however often it is used. `ord()` gives the value in the current [text encoding](https://github.com/Morty40/NopAssembler#text-encoding):

```python
# speedcode.py
def drawText(address, rows):
    positions = {}
    for y, row in enumerate(rows):
        for x, char in enumerate(row):
            if char != ' ':
                positions.setdefault(char, []).append(address + y * 40 + x)

    code = []
    for char, addresses in positions.items():
        code.append(f'lda #{ord(char)}')
        code += [f'sta {target}' for target in addresses]
    return '\n'.join(code)
```

```
            .import "speedcode.py"
            @drawText($0400 + 40*10 + 17, ["#####", "#   #", "##O##"])
```


## Directives

Directives start with a `.`, followed by the name and the arguments, separated by commas. Arguments are Python expressions, so names of files and symbols are written as strings.

### Location

#### .org
```
.org address
```
Sets the current address, where the following code and data is stored. The default is `$1000`.

#### .align
```
.align boundary
```
Advances the current address to the next multiple of `boundary`. Use `.align 256` to place data at the start of a page.

#### .section
```
.section "name", address
.section "name"
```
Switches to a named section, which has its own current address. A new section starts at the address, and an existing one continues where it stopped. Code and data can then be written side by side, also in different files, and stored in separate areas of memory. Here each routine is next to its own sprite, and the sprites are stored together at `$2000`, one after the other:

```
            .section "sprites", $2000
            .section "code", $0810

showPlayer: lda #vicSpritePointer(playerSprite)
            sta $0400 + VIC_SPRITE0_POINTER_OFFSET
            rts

            .section "sprites"
playerSprite:
            .binary "player.spr"    ; 64 bytes

            .section "code"
showEnemy:  lda #vicSpritePointer(enemySprite)
            sta $0400 + VIC_SPRITE1_POINTER_OFFSET
            rts

            .section "sprites"
enemySprite:
            .binary "enemy.spr"     ; 64 bytes
```

Only the first use of a section gives its address, so the main file can set out the memory layout, and imported files just name the sections. The section stays current until the next `.section`. Labels and local labels work across sections as usual.

Sections are stored in one output file, with any gaps between them as 0.

### Data

#### .byte
```
.byte value[, value, ...]
```
Stores bytes. Values from -128 to 255 are allowed.

```
            .byte 1, $02, %11, -1       ; 01 02 03 ff
```

#### .word
```
.word value[, value, ...]
```
Stores 16-bit words, low byte first. Values from -32768 to 65535 are allowed.

```
            .word $1234                 ; 34 12
```

#### .text
```
.text "string"[, "string", ...]
```
Stores strings, using the current text encoding.

#### .string
```
.string "string"[, "string", ...]
```
Like `.text`, but each string is followed by a zero byte.

```
            .encoding ENCODING_SCREEN_UPPER
            .string "ABC", "DEF"        ; 01 02 03 00 04 05 06 00
```

#### .bits
```
.bits "pattern"
```
Stores a bit pattern, 8 bits per byte. A pattern is written with `0` and `1`, or with space and `#` for the 0 and 1 bits, which makes it easy to draw characters and sprites. The two styles can't be mixed in one pattern, and a pattern has 8 bits or a multiple of 8, such as 24 for a sprite row:

```
            .bits "  ####  "            ; 3c
            .bits " ##  ## "            ; 66
            .bits "00011000"            ; 18
```

#### .bytefill
```
.bytefill count[, function]
```
Stores `count` bytes. Without the second argument the bytes are zero. With it, byte `x` is the value of the function for `x`, such as a lambda, a built-in function, e.g. `abs`, or a function or method from a `.python` block or an imported `.py` file, e.g. `util.double`:

```
            .bytefill 4                 ; 00 00 00 00
            .bytefill 4, lambda x: x*2  ; 00 02 04 06
sine:       .bytefill 256, lambda x: int(128 + 127 * sin(x / 128 * pi))
```

A table of the address where each screen row starts saves a multiplication by 40 for every character drawn:

```
SCREEN = $0400

; put the character in a at column x, row y
putChar:    pha
            lda rowLo,y
            sta $fb
            lda rowHi,y
            sta $fc
            txa
            tay
            pla
            sta ($fb),y
            rts

; the address of each of the 25 screen rows, as low and high bytes
rowLo:      .bytefill 25, lambda y: lo(SCREEN + 40 * y)
rowHi:      .bytefill 25, lambda y: hi(SCREEN + 40 * y)
```

When the rule needs more than one expression, write it as a Python function, and give its name:

```
.python
def reverseBits(b):
    """The byte with its bits in reverse order, e.g. %00000001 becomes %10000000."""
    return int(f'{b:08b}'[::-1], 2)
.end

; mirror a byte with a table lookup, instead of moving its bits one at a time
            ldx #%00000011
            lda reversed,x  ; %11000000
            rts

reversed:   .bytefill 256, reverseBits
```

#### .wordfill
```
.wordfill count[, function]
```
Like `.bytefill`, but stores 16-bit words.

A table of the SID frequency of each note, with the C64 target's names: each note is 2^(1/12) times the one before, and the SID's value is the frequency in Hz × 2^24 / the clock rate:

```
; play the note in x on voice 1
playNote:   txa
            asl             ; 2 bytes for each note
            tax
            lda notes,x
            sta SID_VOICE1_FREQUENCY_LO
            lda notes+1,x
            sta SID_VOICE1_FREQUENCY_HI
            rts

; the SID frequency of each note from C-0 to B-6, on a PAL C64, where note 57 is A-4 at 440 Hz
PAL_CLOCK = 985248
notes:      .wordfill 84, lambda n: round(440 * 2 ** ((n - 57) / 12) * 2 ** 24 / PAL_CLOCK)
```

A jump table, where each entry jumps into an unrolled copy, so that only the last n pairs of `lda` and `sta` run:

```
source = $c000
target = $0400
vector = zp(2)

; copy the last x bytes of a 40-byte row, by jumping into the unrolled copy,
; so only the last x of its 40 lda and sta pairs run
copy:       txa
            asl             ; 2 bytes for each entry
            tay
            lda entries,y
            sta vector
            lda entries+1,y
            sta vector+1
            jmp (vector)

.for i in range(40)
            lda source + i
            sta target + i
.end
copyEnd:    rts

; where to start to copy n bytes, for n from 0 to 40: an lda and an sta are 6 bytes
entries:    .wordfill 41, lambda n: copyEnd - 6 * n
```

### Text encoding

#### .encoding
```
.encoding encoding
```
Sets the text encoding used by `.text`, `.string`, `ord()` and `chr()`. The encoding stays in effect until the next `.encoding`.

| Encoding | Description |
|---|---|
| `ENCODING_SCREEN_UPPER` | screen codes, upper case and graphics character set (default) |
| `ENCODING_SCREEN_MIXED` | screen codes, lower and upper case character set |
| `ENCODING_PETSCII_UPPER` | PETSCII, upper case and graphics character set |
| `ENCODING_PETSCII_MIXED` | PETSCII, lower and upper case character set |

An encoding is a table of characters and their values, so you can also use your own, e.g. for a custom font:
```
MY_FONT = {"A": 0, "B": 1, " ": 32}
            .encoding MY_FONT
            .text "AB A"
```
Use screen codes for text written directly to screen memory, and PETSCII for text printed with the KERNAL.

### CPU

#### .cpu
```
.cpu cpu
```
Chooses the cpu, and so the instructions, from the next line on. Each pass starts with the 6502, or the cpu given with `--cpu`, so `.cpu` is usually at the top of the source.

| Cpu | Instructions |
|---|---|
| `CPU_6502` | the documented instructions, and the [illegal instructions](https://github.com/Morty40/NopAssembler#illegal-instructions) that work the same on all C64 and C128 cpus (default) |
| `CPU_65C02` | the documented instructions, and those the 65C02 adds: `bra`, `phx`, `phy`, `plx`, `ply`, `stz`, `trb`, `tsb`, more modes for `bit`, `inc a` and `dec a` as `inc` and `dec` without an operand, `(zp)` for `adc`, `and`, `cmp`, `eor`, `lda`, `ora`, `sbc` and `sta`, and `jmp (address,x)` |
| `CPU_R65C02` | the 65C02's instructions, and the Rockwell bit instructions: `rmb0` to `rmb7` and `smb0` to `smb7` reset and set a bit in zero page, and `bbr0` to `bbr7` and `bbs0` to `bbs7` branch if a bit in zero page is reset or set, e.g. `bbr3 $12,label` |
| `CPU_W65C02` | the R65C02's instructions, and those only the WDC 65C02 has: `wai` waits for an interrupt, and `stp` stops the cpu until a reset |

The mnemonics of all the cpus are instructions, so they can't be used as labels or symbols, also with `CPU_6502`.

```
            .cpu CPU_65C02
            stz $d020
            lda ($fb)
```

```
            .cpu CPU_R65C02
wait:       bbr7 $fb,wait           ; wait until bit 7 of $fb is set
            smb0 $fc                ; set bit 0 of $fc
```

### Files

#### .import
```
.import "filename"[, "namespace"]
```
Imports a file, with the path relative to the folder of the main source file. A `.py` file is executed as Python, so its functions and variables become available to expressions and generators. Any other file is assembled as source code, in place of the `.import` line.

```
            .import "macros.py"
            .import "music.asm"
```

With a namespace, the names a file defines are used as `namespace.name`. A `.py` file runs in a module of that name, as with Python's `import ... as`:

```python
# util.py
def double(x):
    return x * 2

def delay(n):
    return f"""
        ldx #{n}
_loop:  dex
        bne _loop
    """
```

```
            .import "util.py", "util"
            lda #util.double(21)
            @util.delay(100)
```

A source file's labels, local labels and assignments get the namespace in the same way: `draw:` imported into `spr` is `spr.draw`, its local label `_loop` is `spr.draw_loop`, and a constant `SPEED` is `spr.SPEED`, still a constant. The same file can be imported into two namespaces, as each gets labels of its own:

```
; sprites.asm
SPEED = 2
draw:       ldx #SPEED
_loop:      dex
            bne _loop
            rts
```

```
            .import "sprites.asm", "spr"
            jsr spr.draw
            lda #spr.SPEED
```

Code in a namespace uses its own names without the namespace, as in `ldx #SPEED`. Besides those, it only sees the built-in symbols, the ones defined before the source: `lo()`, `zp()`, `ref()` and the others, the `math` names, the target's constants and the `-D` defines. It doesn't see the names of the program, or of a namespace it is inside, so a file can't depend on them by mistake. It gets what it needs as arguments, e.g. `@util.delay(DELAY)`, or imports it itself. The code a generator returns is assembled where the generator is called, so it can use the names there. A namespace keeps names apart, but it isn't a sandbox: the file is still ordinary Python, with the same access to files, network and system, see [Security](https://github.com/Morty40/NopAssembler#security).

From anywhere else, the names in a namespace are used by their full name, e.g. `spr.draw`. A source file's labels are in the labels file and the VICE monitor commands with `_` for `.`, e.g. `spr_draw`, so each is one word, for any tool. Two labels that would be written alike there, such as `spr_draw:` and `draw:` in `spr`, are an error then. Python code in a source file, in `.python` and `.for`, and in a `.py` file it imports without a namespace, defines its names in the namespace too. `ref()` and `.optional` work with the names as the code writes them, e.g. `ref("draw")` inside `spr` and `ref("spr.draw")` outside it, but the names a `.py` file in a namespace uses don't count as references. `_` is still the current address.

Files imported into the same namespace share it, also a `.py` file and a source file: the source can call the `.py` file's functions, and the `.py` file can use the source's labels. A file in a namespace can import another one into a namespace inside it: `draw` in `util` in `spr` is `spr.util.draw`, written `spr_util_draw`. A file imported without a namespace is in the namespace of the file that imports it.

Python's `global` statement doesn't work in a source file's namespace, as Python stores such a name where the namespace can't see it. Keep the state in a container instead, e.g. `counts = [0]`, and `counts[0] += 1` in a function.

The namespace is a name that isn't a Python keyword or built-in, such as `len`, doesn't start with `_`, and isn't another symbol, such as a label. All capitals are fine: `.import "sid.asm", "SID"` gives `SID.play`.

#### .binary
```
.binary "filename"[, offset[, length]]
```
Stores the contents of a binary file, with the path relative to the folder of the main source file. With an offset, the bytes before it are skipped, and with a length, only that many bytes are stored:
```
            .binary "sprites.bin", 64, 128 ; the second and third sprite
```

### Repetition

#### .repeat, .end
```
.repeat count
...
.end
```
Assembles the lines up to `.end` `count` times. With a count of 0, the lines are skipped. `.repeat`, `.for` and `.if` blocks can be nested, and `.end` ends the innermost one. For a counter variable, use `.for`.

```
            .repeat 8
            nop
            .end
```

#### .for, .end
```
.for target in iterable
...
.end
```
Assembles the lines up to `.end` for each value of the iterable, as Python's `for` does, with the value assigned to the target. The iterable is any Python expression, such as `range(8)`, a list, a string or a generator, and the target is a name, or names to unpack each value into, where a name with `*` gets the rest of the values as a list, as in Python. If there are no values, the lines are skipped.

```
            .for row in range(4)
            .for column in range(4)
            .byte row * 16 + column
            .end
            .end

            .for x, y in [(24, 50), (320, 229)]
            .word x
            .byte y
            .end

            .for first, *rest in [(3, 10, 20, 30)]
            .byte first, len(rest) ; 3 and 3, with rest as [10, 20, 30]
            .end
```

After the loop, the target keeps its last value. A loop that has not ended after 65536 rounds, e.g. over an endless iterator, is an error.

As in Python, every name in the target is assigned, also `_`, which is the [current address](https://github.com/Morty40/NopAssembler#labels). So `.for _ in range(8)` moves the current address in each round: use `.repeat 8` for lines that only repeat, and another name, such as `unused`, for a value that isn't used.

### Conditions

#### .if, .elif, .else, .end
```
.if condition
...
.elif condition
...
.else
...
.end
```
Assembles the lines up to `.elif`, `.else` or `.end` if the Python expression `condition` is true. Otherwise, as in Python, the lines of the first `.elif` with a true condition are assembled, or else the lines from `.else` to `.end`. The `.elif` and `.else` parts are optional, and there can be more than one `.elif`. The lines that are not assembled can define the same labels.

```
            .if DEBUG
            inc $d020
            .else
            nop
            .end
```

A chain of `.elif` picks one of several choices, such as the timing of the three video chips of the C64, with an `.else` that catches a misspelled choice:

```
VIDEO = "PAL"                           ; or "NTSC" or "OLD_NTSC"

            .if VIDEO == "PAL"          ; 6569
LINES = 312
CYCLES = 63
            .elif VIDEO == "NTSC"       ; 6567R8
LINES = 263
CYCLES = 65
            .elif VIDEO == "OLD_NTSC"   ; 6567R56A
LINES = 262
CYCLES = 64
            .else
            .error "Unknown VIDEO: {VIDEO}"
            .end
```

With `ref("label")` as the condition, a library of code and data only adds what the program needs:

```
            jsr clearScreen

            .if ref("clearScreen")      ; assembled, as clearScreen is referenced
clearScreen:
            lda #$20
            rts
            .end

            .if ref("myTable")          ; not referenced, so nothing is stored
myTable:    .byte 1, 2, 3
            .end
```

`ref` is false in the first pass, so a block starts out left out, and is added in the following passes once something references its label. A block that only references itself is never added. Symbols set in a block that is left out are not defined.

With `has("instruction")` as the condition, code can use the best instructions of the [cpu](https://github.com/Morty40/NopAssembler#cpu), and still assemble for the others. It is true if that line would assemble on the current cpu, so `has("lax $12")` is true on the 6502, and false on the 65C02s, which don't have `lax`. The operand shows which address mode to ask about, so a plain number is best: `$12` means zero page.

The illegal `lax` loads both A and X:

```
index = zp(1)

            .if has("lax $12")            ; 2 bytes, 3 cycles
            lax index
            .else                         ; 3 bytes, 5 cycles
            lda index
            tax
            .end
```

The 65C02s can push X and Y directly, which helps at the start of an interrupt routine:

```
irq:
            .if has("phx") and has("phy") ; 3 bytes, 9 cycles
            pha
            phx
            phy
            .else                         ; 5 bytes, 13 cycles
            pha
            txa
            pha
            tya
            pha
            .end
```

The Rockwell and WDC 65C02s can set a single bit in zero page, without changing A, and all 65C02s can set the bits of A in memory with `tsb`. As only the first true condition counts, `smb3` is used where both are available:

```
flags = zp(1)

            .if has("smb3 $12")           ; 2 bytes, 5 cycles
            smb3 flags
            .elif has("tsb $12")          ; 4 bytes, 7 cycles
            lda #%00001000
            tsb flags
            .else                         ; 6 bytes, 8 cycles
            lda flags
            ora #%00001000
            sta flags
            .end
```

#### .optional, .end
```
.optional
...
.end
```
Like `.if` with `ref` of each label in the block, so the names are not repeated. The lines up to `.end` are assembled if any of the block's labels is referenced, a local label by its full name:

```
            jsr func2

            .optional           ; assembled, as func2 is referenced
func1:      nop
            rts
func2:      nop
            rts
            .end

            .optional           ; not referenced, so nothing is stored
myTable:    .byte 1, 2, 3
            .end
```

Only labels written directly in the block count, so not assignments such as zero page variables, or labels from generated code or an imported file. A block without labels is never assembled. A nested block is only assembled if the outer block is, and each block only checks its own labels. For anything else, use `.if` with `ref`.

### Python

#### .python
```
.python
...
.end
```
Executes the block of Python code up to `.end`, for example to define functions. The lines are passed to Python unchanged, so `;`, `$` and `%` keep their Python meaning. The block can be indented like the assembly around it, as long as the indentation within it is consistent.

```
            .python
                def double(x):
                    return x * 2

                def nops(n):
                    return "nop\n" * n
            .end

            .byte double(21)
            @nops(3)
```

### Messages

#### .print
```
.print value[, value, ...]
```
Prints values to the terminal. The source is assembled in multiple passes, and the values are printed once, from the last pass, so they are final.

#### .warning
```
.warning "message"
```
Reports a warning. Assembly continues.

#### .error
```
.error "message"
```
Reports an error. The output file is not written.

#### .assert
```
.assert condition[, "message"]
```
Reports an error if the Python expression `condition` is false, with the message, or `Assertion failed` without one. The condition is checked in the last pass, so it can use labels defined later. For example, to check the memory layout:

```
            .assert _ <= $1000, "The code overlaps the music at $1000"
            .assert hi(table) == hi(tableEnd - 1), "The table crosses a page"
            .assert sprite % 64 == 0
```

#### .break
```
.break ["condition"]
```
Sets a breakpoint in VICE at the current address, written to the [VICE monitor commands](https://github.com/Morty40/NopAssembler#vice-monitor-commands) file. The optional condition is passed to VICE unchanged, in VICE's own format: registers `A`, `X`, `Y`, `SP`, the raster line `RL` and cycle `CY`, and hex numbers with `$`:

```
irq:        .break                      ; stop each time the interrupt starts
            lda VIC_INTERRUPT_REGISTER
            .break "RL > $40"           ; stop only if the raster line is past $40
```


## Built-in symbols

The Python files in `nopa/imports/` are always imported, and are not specific to one machine. The upper case symbols are [constants](https://github.com/Morty40/NopAssembler#constants):

| File | Contents |
|---|---|
| `stack.py` | `STACK_ADDRESS`, and generators: `pushRegisters()`, `pullRegisters()`, `storeRegisters(restore)`, `restoreRegisters()` |
| `utility.py` | generators: `nop(n)`, `ldax(value)`, `lday(value)`, `ldxy(value)`, `stax(address)`, `stay(address)`, `stxy(address)` |
| `vector.py` | interrupt vectors, `INTERRUPT_VECTOR_...` |

For example `@ldax(message)` loads the address of `message` into A (low byte) and X (high byte).

`SOURCE_FOLDER` is the folder of the main source file, for generators that read files.

`-t` or `--target` also imports all the files of a target machine, from `nopa/imports/target/`. Without it, no target files are imported, so a symbol such as `VIC_BORDER_COLOR` is not defined.

| Target | File | Contents |
|---|---|---|
| `c64` | `basic.py` | [BASIC 2.0](https://github.com/Morty40/NopAssembler#basic), `BASIC_START_ADDRESS` (`$0801`), and `BASIC_ROM` |
| `c64` | `cia.py` | CIA 1 and 2 registers, `CIA1_...` and `CIA2_...` |
| `c64` | `ioport.py` | the 6510 processor port at `$00` and `$01`, `IO_PORT_DATA_DIRECTION` and `IO_PORT_DATA`, which chooses RAM, ROM or I/O at `$a000`, `$d000` and `$e000` |
| `c64` | `kernal.py` | KERNAL ROM routines, `KERNAL_ROM_...` |
| `c64` | `keyboard.py` | keyboard matrix codes, `KEYBOARD_CODE_...` |
| `c64` | `machine.py` | `CHAR_ROM` |
| `c64` | `music.py` | SID music files, and the generator `importMusic(file, prefix)` |
| `c64` | `sid.py` | SID registers, `SID_...` |
| `c64` | `vic.py` | VIC-II registers, `VIC_...` |
| `c16` | `basic.py` | [BASIC 3.5](https://github.com/Morty40/NopAssembler#basic), `BASIC_START_ADDRESS` (`$1001`), and `BASIC_ROM` |
| `c16` | `kernal.py` | KERNAL ROM routines, `KERNAL_ROM_...` |
| `c16` | `machine.py` | `SCREEN_RAM` and `COLOR_RAM` |
| `c16` | `ted.py` | TED registers and colors, `TED_...`, and `tedColor(color, luminance)` |
| `plus4` | | the same files as `c16` |
| `c128` | `basic.py` | [BASIC 7.0](https://github.com/Morty40/NopAssembler#basic), `BASIC_START_ADDRESS` (`$1C01`), and `BASIC_ROM` |
| `c128` | `cia.py`, `sid.py`, `vic.py`, `ioport.py` | the same as `c64` |
| `c128` | `kernal.py` | KERNAL ROM routines, `KERNAL_ROM_...` |
| `c128` | `machine.py` | `SCREEN_RAM`, `COLOR_RAM` and `CHAR_ROM`, in 40 columns |
| `c128` | `mmu.py`, `vdc.py` | MMU and VDC registers, `MMU_...` and `VDC_...` |
| `vic20` | `basic.py` | [BASIC 2.0](https://github.com/Morty40/NopAssembler#basic), `BASIC_START_ADDRESS` (`$1001`, without a memory expansion), and `BASIC_ROM` |
| `vic20` | `kernal.py` | KERNAL ROM routines, `KERNAL_ROM_...`, without `SCINIT`, `IOINIT` and `RAMTAS` |
| `vic20` | `machine.py` | `SCREEN_RAM` and `COLOR_RAM`, and `SCREEN_RAM_EXPANDED` and `COLOR_RAM_EXPANDED` with 8K or more of memory expansion |
| `vic20` | `via.py` | VIA 1 and 2 registers, `VIA1_...` and `VIA2_...` |
| `vic20` | `vic.py` | VIC registers and colors, `VIC_...` |
| `cx16` | `basic.py` | [BASIC 2.0](https://github.com/Morty40/NopAssembler#basic), `BASIC_START_ADDRESS` (`$0801`), and `BASIC_ROM`, in ROM bank 4 |
| `cx16` | `kernal.py` | the C64's KERNAL ROM routines, `KERNAL_ROM_...`, at the same addresses, and `KERNAL_R0` to `KERNAL_R15`, the 16-bit registers in zero page for the X16's own KERNAL calls |
| `cx16` | `machine.py` | the bank registers `RAM_BANK` and `ROM_BANK`, the windows `BANKED_RAM` and `BANKED_ROM`, the ROM banks `ROM_BANK_...`, and the zero page free for programs, `ZERO_PAGE_USER` to `ZERO_PAGE_USER_END` |
| `cx16` | `vera.py` | VERA registers, `VERA_...`, and its VRAM layout, `VERA_VRAM_...` |
| `cx16` | `via.py` | VIA 1 and 2 registers, `VIA1_...` and `VIA2_...` |
| `cx16` | `ym2151.py` | the YM2151's ports, `YM2151_ADDRESS` and `YM2151_DATA`, and the numbers of its internal registers, `YM2151_REGISTER_...`, to write to `YM2151_ADDRESS`. For a channel's register add the channel, 0-7, and for an operator's also 8 times the operator, 0-3 |

The `cx16` target, for the Commander X16, is experimental: it hasn't been tried on an emulator or the real machine yet. The X16 has a WDC 65C02, so use `.cpu CPU_W65C02` or `--cpu W65C02` for its instructions. Its KERNAL uses `$02`-`$21` in zero page, where `zp()` starts, so with the X16's own KERNAL calls, reserve those bytes first, and `zp()` continues from `ZERO_PAGE_USER`: `kernalZeroPage = zp(ZERO_PAGE_USER - 2)`.

`importMusic(file, prefix)`, with `-t c64`, stores the music data from a SID file, without the header. PSID versions 1 to 4 and RSID versions 2 to 4 are supported, but not Compute!'s Sidplayer MUS data. The symbols `prefix_LOAD`, `prefix_INIT` and `prefix_PLAY` are defined with the load, init and play addresses. The path is relative to the folder of the main source file:

```
            .org MUSIC_LOAD
            @importMusic("song.sid", "MUSIC")
            ...
            jsr MUSIC_INIT
```

### BASIC

Each target has the BASIC version of its machine: 2.0 on the `c64`, `vic20` and `cx16`, 3.5 on the `c16` and `plus4`, and 7.0 on the `c128`. Its `basic.py` defines:

- the tokens, `BASIC_TOKEN_...`, named after the keywords without `$` and `(`, such as `BASIC_TOKEN_CHR` for `CHR$`, or after the characters, such as `BASIC_TOKEN_PLUS` for `+` and `BASIC_TOKEN_PRINT_FILE` for `PRINT#`, and `BASIC_TOKEN_PI` for the pi character
- generators for a BASIC start line: `basicStart()`, which sets the address to `BASIC_START_ADDRESS`, `basicLine(lineNumber, text)`, `basicSys(lineNumber, address)`, a line with just a `SYS` to the address, and `basicEnd()`

`basicLine` writes any BASIC line, with the keywords of the target's BASIC as tokens, including the two-byte tokens of BASIC 7.0, such as `BANK`. Keywords of a later version are converted as when typed on the machine: on the C64, `GRAPHIC` stays as text, and `COLOR` becomes `COL` and the token of `OR`. Both give a syntax error when the program runs:

```
            @basicStart()
            @basicLine(10, 'POKE 53280,0:PRINT "HELLO"')
            @basicLine(20, "SYS {start}")
            @basicEnd()
```

The versions are defined in `nopa/basic.py`, with the keywords as in the ROMs: `BASIC_1`, `BASIC_2`, `BASIC_3_5`, `BASIC_4`, `BASIC_4_PLUS` and `BASIC_7`. BASIC 1.0 and 4.0 of the PET, and 4.0+ of the CBM-II, are ready for future targets.


## Passes, warnings and errors

Nop Assembler is a multi-pass assembler: it assembles the source in multiple passes, until the output no longer changes. This resolves forward references, and lets the size of instructions depend on labels defined later in the source. Errors are reported from the final pass only.

Warnings do not stop the output from being written. They are given when:
- a memory location is written more than once
- a float value is truncated to an integer
- `jmp (address)` has its address on a page boundary, on the 6502

When the function of a `.bytefill` or `.wordfill` fails for a value, the error names the index, e.g. `List index out of range, at index 2`, and the value is zero, so the size stays the same.


## Security

Assembling a source file runs Python code: expressions, generators, `.python` blocks, `.for` loops and imported `.py` files are all executed, with the same access to files, network and system as any Python program. Only assemble source files you trust, just as you would only run Python scripts you trust.


## Development

To work on Nop Assembler, clone the repository:

```bash
git clone https://github.com/Morty40/NopAssembler.git
```

```bash
cd NopAssembler
```

Then install it from the local folder in editable mode:

```bash
pipx install --editable .
```

The `nopa` command then runs the source in the repository, so changes take effect without reinstalling, also when you use it from another project. Only changes to `pyproject.toml`, such as the version or the command name, need a reinstall with `pipx install --force --editable .`. If `nopa` is already installed from PyPI or GitHub, add `--force` the first time too, to replace it. Without `--editable`, `pipx install .` installs a copy of the source as it is now.

Nop Assembler can also run directly from the repository folder, without installing:

```bash
python3 -m nopa hello.asm -t c64 -o hello.prg
```

### Running the tests

```bash
cd nopa
make test
```

`make test` runs the unit tests in `nopa/tests/`.


## Changelog

What's new in each version is in [CHANGELOG.md](https://github.com/Morty40/NopAssembler/blob/main/CHANGELOG.md).


## License

MIT, see [LICENSE.txt](https://github.com/Morty40/NopAssembler/blob/main/LICENSE.txt).
