Functions
R65 functions map directly to 65816 subroutines. The calling convention is explicit: the programmer specifies how each parameter is passed and how values are returned.
Function Declaration
fn name(parameters) -> ReturnType {
body
}
Every function is far by default: callable from any bank. near fn opts out (see Near vs Far Calls). A function without a return type annotation returns nothing.
fn add_one(value @ A: u8) -> u8 {
return value + 1;
}
Parameter Passing
R65 provides three parameter-passing mechanisms.
Comparison
| Mechanism | Syntax | Limit | Reentrant |
|---|---|---|---|
| Stack | param: Type | Unlimited | Yes |
| Register | param @ A: u8 | 4 registers | Yes |
| Variable-bound | param @ VAR: Type | Unlimited | No |
Ordering rule: Stack parameters must appear before register and variable-bound parameters. The compiler rejects any other ordering.
// Valid: stack parameters first
fn process(count: u8, flags: u8, value @ A: u8) -> u8 { ... }
// Invalid: stack parameter after register parameter
fn bad(value @ A: u8, count: u8) { } // compile error
Stack Parameters
Syntax: param: Type
Stack parameters are pushed by the caller in right-to-left order and cleaned up by the caller after the call. They support recursion and have no limit on count.
fn add(a: u8, b: u8) -> u8 {
return a + b;
}
let result = add(10, 20);
Register Parameters
Syntax: param @ Register: Type
The caller places the value directly in the specified hardware register. This is the fastest mechanism.
Available registers:
| Register | Type Constraint | Notes |
|---|---|---|
A | u8 (default) or u16 | u16 switches function to m16 mode |
X | u16 only | Always 16-bit (x16 mode) |
Y | u16 only | Always 16-bit (x16 mode) |
B | u8 only | m8 mode only; high byte of accumulator |
X and Y parameters must be u16. The compiler rejects @ X: u8 or @ Y: u8.
fn plot(x @ X: u16, y @ Y: u16, color @ A: u8) {
// X, Y, A already contain the arguments
}
When the caller already has values in the correct registers, the call has zero setup cost.
B Register Parameters
The B register (high byte of the 16-bit accumulator) is available as a parameter in m8 mode.
fn pack(low @ A: u8, high @ B: u8) -> u16 {
return A as u16 | ((B as u16) << 8);
}
B cannot be used when the function has a @ A: u16 parameter (m16 mode), because the full 16-bit accumulator is in use.
Variable-Bound Parameters
Syntax: param @ VARIABLE: Type
The caller writes the argument to a specific memory location (typically a zero-page variable), and the callee reads from that address.
#[zeropage(0x10)]
static mut INPUT_X: u8;
#[zeropage(0x11)]
static mut INPUT_Y: u8;
fn compute(x @ INPUT_X: u8, y @ INPUT_Y: u8) -> u8 {
return x + y;
}
Variable-bound parameters are not reentrant because they use shared global storage. This mechanism is common in hand-written SNES assembly.
Mixed Parameters
All three mechanisms can be combined in a single function signature, as long as stack parameters come first.
fn mixed(count: u8, base @ A: u8, offset @ TEMP: u8) -> u8 {
// count on stack, base in A, offset in TEMP zero-page variable
}
Return Values
Implicit A Return
A function with a -> Type return annotation and no explicit return statement returns whatever is in the A register.
fn get_status() -> u8 {
A = STATUS & 0x0F;
// Implicitly returns A
}
Explicit Return
Use return followed by registers or variables.
fn get_value() -> u8 {
return A;
}
fn get_index() -> u16 {
return X;
}
Multiple Return Values
Functions can return up to four values by listing their types after ->. No parentheses around the return list, and no register names — the compiler maps each value to a register from its type and the function's mode.
fn divide(dividend @ A: u8, divisor @ X: u16) -> u8, u16 {
// quotient in A, remainder in X
return A, X;
}
Return type list: -> u8, u8, -> u8, u16, -> u16, u16, etc. Values are assigned to registers in order: the first to A (mode-width), the second to B when it is 8-bit in m8 mode (otherwise X), then X and Y. X and Y are always 16-bit, so the third and fourth values must be 16-bit types, and a fourth value is only possible when the second is 8-bit in m8 mode (which frees B).
// A and B (both u8, m8 mode — B avoids a TAX)
fn unpack(word: u16) -> u8, u8 {
A = word as u8;
B = (word >> 8) as u8;
return A, B;
}
// A and X (u8 + u16)
fn compute() -> u8, u16 {
A = 42;
X = 1000;
return A, X;
}
Caller captures with multi-binding:
let quotient, remainder = divide(100, 7);
Far Pointer Returns
A function may return a far pointer, -> far *T or a far fn(). Three bytes fit no register, so the value comes back split: its bank byte in A and its low 16 bits in X, the registers a -> u8, u16 return uses, and the function exits in m8. The caller puts the two halves back together, so the returned pointer is an ordinary value that stays valid across later calls. Because X carries part of it, such a function cannot list X in #[preserves(...)], and an extern fn declared this way must leave the bank in A and the low 16 bits in X. A far pointer must be the only value returned; it cannot be one of several.
fn tile_row(row: u16) -> far *u8 {
return &TILEMAP[row * 32];
}
Return Signature Consistency
Every return must supply one value per type in the declared return list, each of that type. The registers follow from the types (see Multiple Return Values), so all paths return in the same registers by construction.
// Valid: every path returns (u8, u16)
fn branch(flag: u8) -> u8, u16 {
if flag != 0 {
return 1, 2;
}
return 3, 4;
}
// Invalid: one path returns a single value
fn bad(flag: u8) -> u8, u16 {
if flag != 0 {
return 1, 2;
}
return 3; // error: returning 1 value from a function declared '-> u8, u16'
}
Never Return Type
Functions that never return use -> !. The compiler omits RTS/RTL. Common for entry points and error handlers.
#[entry]
fn main() -> ! {
init();
loop {
update();
wait_for_vblank();
}
}
fn fatal_error() -> ! {
A = 0x80; // force blank
loop { }
}
If control can reach the end of a -> ! function, or a return in it, the compiler emits a branch-to-self halt loop there instead of a return.
Near vs Far Calls
Far Functions (the default)
Syntax: fn name() { }
Every function is far unless it says otherwise: free functions, methods, trait methods and extern fn alike. A far function is called with JSL/RTL and a 24-bit address, so it is callable from any bank. Writing far fn pins a function far: the optimizer never turns it into a near call, even when every caller shares its bank. Use it only when code the compiler cannot see, such as hand-written assembly, calls the function with JSL. It is an error on the entry function and interrupt handlers.
#[bank(1)]
fn sound_engine() {
// Lives in bank 1, callable from anywhere
}
A function in a multi-bank ROM gets called from wherever it is useful, so the default that needs no thought is the one that works everywhere.
Near Functions
Syntax: near fn name() { }
A near function is called with JSR/RTS and a 16-bit address, so it can only be called from within its own bank.
near fn helper() -> u8 {
return A;
}
The #[entry] function and #[interrupt] handlers are reached through the CPU's vectors rather than called, so the far default does not apply to them.
Cross-Bank Call Rules
| Caller Bank | Callee Bank | Callee Type | Allowed |
|---|---|---|---|
| Any | Any | fn (far by default) | Yes |
| 0 | 0 | near fn | Yes |
| 0 | 1 | near fn | No -- compile error |
| 1 | 0 | near fn | No -- compile error |
Near functions use a 16-bit address and cannot cross bank boundaries. The compiler enforces this at compile time.
Methods
Methods follow the same rule: a fn inside an impl or trait block is far, and near fn opts it into JSR/RTS.
impl Player {
fn heal(*self) { } // far call (JSL/RTL), near self pointer
near fn tick(*self) { } // near call (JSR/RTS), same bank only
}
trait Drawable { fn draw(*self); } // far trait
trait Ticker { near fn tick(*self); } // near trait
The calling convention and the self pointer are independent: fn m(*self) is a far call with a near self, near fn m(far *self) a near call with a far self.
Rules:
- A trait's methods must all be near or all be far (the dispatch wrapper is built per trait), and an impl method must match its trait's convention.
near fnis an error in#[bank(auto)]mode.- A function called from hand-written
asm!should be declarednear fnand called withJSR. The compiler cannot see calls insideasm!, so it does not account for them when choosing a function's calling convention.
Cost
The far default is free in practice for direct calls: at -O1 and above the compiler demotes any far function whose direct callers all sit in its own bank back to JSR/RTS, so a same-bank program compiles to exactly what it would with near fn everywhere. Three things are not demoted:
- A function whose address is taken. A call through a pointer uses the pointer type's convention, so the function keeps it (see Function Pointers).
*dyndispatch. A far trait's wrapper is a JSL plus a JML trampoline (~20–25 cycles) against ~10–12 for a near trait, so a trait dispatched in a hot loop should be declared withnear fn.- A function nothing calls directly, such as one reached only from
asm!.
Inlining is likewise unaffected: a far function in the caller's bank inlines exactly as a near one would. (Trait-impl methods are never inlined.)
Bank Placement
#[bank(n)] sets the bank context for all subsequent function and ROM data declarations until the next #[bank] directive.
#[bank(0)]
fn main_loop() { } // Bank 0
#[bank(1)]
fn audio_tick() { } // Bank 1
fn audio_init() { } // Also bank 1 (inherits)
#[bank(auto)]
fn auto_placed() { } // Compiler chooses bank
In #[bank(auto)] mode, a function must not be near fn, and all immutable statics must use far static.
Data Bank Register Management
Far functions can specify how the Data Bank Register (DBR) is handled via #[mode(databank=...)]. This controls which bank is used for absolute address data access.
databank=none (default)
No DBR management. The programmer is responsible for ensuring DBR is correct.
#[bank(1)]
fn raw_access() {
// DBR is whatever the caller left it as
}
databank=inline
The callee saves, sets, and restores DBR automatically.
#[bank(1)]
#[mode(databank=inline)]
fn managed_access() {
// DBR = 1 inside this function
}
databank=caller
The caller is responsible for setting DBR before the call. Useful for batching multiple far calls to the same bank.
#[bank(1)]
#[mode(databank=caller)]
fn caller_managed() {
// Expects caller to have set DBR = 1
}
Register Preservation
By default, all registers are caller-save: the caller must save any register it needs across a function call. The #[preserves(...)] attribute changes specific registers to callee-save.
#[preserves(X, Y)]
fn safe_function(value @ A: u8) -> u8 {
X = 100; // Modified freely inside
Y = 200; // Modified freely inside
return value;
}
// X and Y are guaranteed unchanged after call
Valid registers for preservation: A, X, Y, STATUS, D, DBR
Invalid registers for preservation: B (shares hardware with A), PBR (read-only), S (stack pointer)
A is valid only on a function that returns nothing (or is -> !, which never reaches its epilogue). The first return value travels in A, and the restore at exit would overwrite it:
#[preserves(A)]
fn bad(value @ A: u8) -> u8 { return value; }
// type error: A cannot be in #[preserves(...)] on a function that returns a value
Const Functions
Functions declared with const fn can be evaluated at compile time when all arguments are constants. When called with runtime arguments, they compile to a normal function call.
const fn tile_offset(x: u8, y: u8) -> u16 {
return (y as u16) * 32 + (x as u16);
}
// Compile-time evaluation: folded to literal 163
const PLAYER_TILE: u16 = tile_offset(3, 5);
// Runtime call
fn get_offset(px: u8, py: u8) -> u16 {
return tile_offset(px, py);
}
What a const function can do:
- Arithmetic with
*,/and%on any operands, not just powers of two./and%truncate toward zero. - Control flow:
if/else,while,for(including..=),loopwithbreak value,match, and labeledbreak/continue. - Local variables, arrays, structs, type casts, newtypes and enums.
- Calls to other const functions and to const methods (
Type::name(...)), including recursion up to 256 calls deep. - Use of consts and const functions declared further down the file.
Values wrap at their type's width exactly as they would at runtime. For example, a u8 that reaches 256 is 0, and the result is converted to the declared return type. A const function therefore gives the same answer whether the compiler evaluates it or the 65816 runs it.
When every argument is constant, the call must be evaluated at compile time. An error inside it is reported with its cause, for example division by zero, an index out of bounds, or more than 1,000,000 loop passes. The call is not silently left for runtime.
Const function restrictions:
- No hardware register access (
A,X,Y, etc.) - No reading or writing runtime variables
- No
asm!()blocks - A body that uses
*,/or%in a form the runtime rules reject can only be called with constant arguments; a call with a runtime argument is a compile error naming the operator
Function Pointers
Function pointers store the address of a function for indirect calls.
| Type | Call Mechanism | Pointer Size |
|---|---|---|
fn(u8) -> u8 | Far (any bank), the default | 24-bit |
near fn(u8) -> u8 | Near (same bank) | 16-bit |
The two are distinct types: a fn(...) pointer holds a far function and a near fn(...) pointer a near one. Use the near form when the pointer must be 2 bytes, for example in a newtype or a large dispatch table, and declare its targets near fn.
type Callback = fn(u8) -> u8;
#[ram]
static mut HANDLER: Callback;
fn dispatch(input @ A: u8) -> u8 {
return HANDLER(input);
}
Structs, Unions, and Arrays as Parameters
Structs, unions, and arrays cannot be passed by value or returned by value. Use pointers instead.
struct Player { x: u8, y: u8, health: u16 }
// Invalid: pass by value
fn bad(player: Player) { } // compile error
// Valid: pass by pointer
fn damage(player: *Player, amount @ A: u8) {
player.health = player.health - amount as u16;
}
// Valid: return pointer
fn get_player() -> *Player {
return &PLAYER;
}
This restriction makes memory access costs explicit.
It does not apply to newtypes. A single-positional-field struct such as struct TileId(u8); is a scalar, not an aggregate, so it is passed and returned by value in a register like any u8:
struct TileId(u8);
fn next(t @ A: TileId) -> TileId { return t + 1; } // by value, in A
Newtype methods likewise take bare self by value, bound to A.
Processor Mode and Functions
CPU mode is automatically inferred from parameter types. There is no manual mode annotation for processor mode.
- Default: m8 (8-bit accumulator), x16 (16-bit index registers)
- m16 mode: Inferred when a function has
@ A: u16 - X/Y: Always u16 -- the compiler rejects
@ X: u8or@ Y: u8
// m8 mode (default)
fn process_byte(value @ A: u8) -> u8 {
return value + 1;
}
// m16 mode (inferred from u16 @ A)
fn process_word(value @ A: u16) -> u16 {
return value + 1;
}
The #[mode(...)] attribute is only used for data bank management (databank=none|inline|caller), not for CPU mode.