Expressions
R65 provides operators and functions that clearly distinguish between hardware-supported operations (fast) and software-implemented operations (slow).
- Operators (
+,-,*,/,<<,>>, etc.) map directly to 65816 instructions or short instruction sequences. Cost: 2--10 cycles. - Functions (
mul8()/mul16(),div8()/div16(),mod8(),shl8()/shl16(),shr8()/shr16()) are standard-library subroutines inmath.r65for operations the instructions cannot do directly. They needinclude!("lib/math.r65"). Cost: ~8--30 cycles on the SNES hardware math units, hundreds in software — see Math Library.
All arithmetic is unchecked. Overflow wraps, underflow wraps, and division by zero is undefined behavior. There are no runtime checks.
Operator Summary
| Category | Operators | Restrictions | Cycles |
|---|---|---|---|
| Arithmetic | +, - | None | 2--4 |
| Multiply | * | Right operand must be power-of-2 constant (1–256) | 2--16 |
| Divide | / | Right operand must be power-of-2 constant (1–256) | 2--16 |
| Left shift | << | Right operand must be a compile-time constant | 2 per bit |
| Right shift | >> | Right operand must be a compile-time constant | 2 per bit |
| Bitwise | &, |, ^, ~ | None | 2--4 |
| Comparison | ==, !=, <, >, <=, >= | None | 4--6 (unsigned), 8--15 (signed) |
| Logical | &&, ||, ! | Operands must be bool | 4--8 |
| Unary minus | - (prefix) | None | 4--6 |
| Bitwise NOT | ~ | None | 2--4 |
| Compound assign | +=, -=, &=, |=, ^=, <<=, >>= | Inherit base operator restrictions | Same as base |
| Multiply assign | *= | Right operand must be power-of-2 constant (1–256) | 2--16 |
| Divide assign | /= | Right operand must be power-of-2 constant (1–256) | 2--16 |
| Increment | x++ | Postfix only, statement-only | 2--6 |
| Decrement | x-- | Postfix only, statement-only | 2--6 |
| Type cast | as | See Type Conversions | 0--8 |
Arithmetic
Addition and Subtraction
+ and - have no restrictions. They accept any integer operands and wrap on overflow.
let sum: u8 = a + b; // CLC; ADC (2-4 cycles)
let diff: u8 = a - b; // SEC; SBC (2-4 cycles)
// Overflow wraps silently
let x: u8 = 255 + 1; // result: 0
let y: u8 = 0 - 1; // result: 255
The compiler optimizes a + 1 and a - 1 to INC / DEC instructions when possible.
Restricted Multiply
The * operator only accepts power-of-2 constants from 1 to 256 as the right operand. The compiler translates these to shift instructions.
let x: u8 = a * 2; // ASL (2 cycles)
let y: u8 = a * 4; // ASL; ASL (4 cycles)
let z: u8 = a * 8; // ASL; ASL; ASL (6 cycles)
let w: u8 = a * 64; // 6x ASL (12 cycles)
let e: u8 = a * 3; // COMPILE ERROR: use mul8(a, 3)
let f: u8 = a * b; // COMPILE ERROR: use mul8(a, b)
For general multiplication, use the mul8() / mul16() functions.
Restricted Divide
The / operator only accepts power-of-2 constants from 1 to 256 as the right operand. The compiler translates these to right shifts.
let x: u8 = a / 2; // LSR (2 cycles)
let y: u8 = a / 4; // LSR; LSR (4 cycles)
let z: u8 = a / 8; // LSR; LSR; LSR (6 cycles)
let w: u8 = a / 64; // 6x LSR (12 cycles)
let e: u8 = a / 3; // COMPILE ERROR: use div8(a, 3)
let f: u8 = a / b; // COMPILE ERROR: use div8(a, b)
Signed division (i8, i16) rounds toward zero, as in Rust: -7 / 2 is -3. A negative dividend is adjusted before the shift, so signed division costs a few cycles more than unsigned, plus about twice as much per bit shifted.
For general division, use the div8() / div16() functions.
The power-of-2 rules for * and / exist because of the code a runtime operation needs. Where no code is generated they don't apply: an expression whose operands are all constants, such as const H: u16 = W * 13 / 3 % 10;, is computed by the compiler, and so is everything inside a const fn called with constant arguments. Compile-time / and % truncate toward zero, so -7 / 2 is -3 and -7 % 2 is -1.
Shift Operators
Left Shift and Right Shift
<< and >> require the shift amount to be a compile-time constant. Each bit of shift compiles to one ASL (left) or LSR (right) instruction.
let x: u8 = a << 3; // ASL; ASL; ASL (6 cycles)
let y: u8 = a >> 2; // LSR; LSR (4 cycles)
let z: u8 = a << n; // COMPILE ERROR: use shl8(a, n)
let w: u8 = a >> n; // COMPILE ERROR: use shr8(a, n)
On unsigned types >> is a logical shift (fills with zeros). On signed types (i8, i16) it is an arithmetic shift: it fills with copies of the sign bit, so it rounds toward negative infinity (-7 >> 1 is -4, where -7 / 2 is -3). The 65816 has no arithmetic shift instruction, so each bit of a signed shift costs about twice as much as an unsigned one. Shifting a run-time value by an amount greater than or equal to its bit width is a compile error, since no bit of it would survive: widen it first, as in (b as u16) << 10.
A shift whose value lands in a wider destination is computed at the destination's width, whether it is assigned directly or packed in with |, &, ^, + or -. With hi and lo both u8, let w: u16 = (hi << 8) | lo; shifts hi as a u16 rather than losing it to an 8-bit shift.
For variable shift amounts, use the shl8() / shl16() and shr8() / shr16() functions.
Bitwise Operators
&, |, ^, and ~ have no restrictions and map directly to 65816 instructions (AND, ORA, EOR).
let masked: u8 = value & 0x0F; // AND: mask low nibble
let combined: u8 = high | low; // ORA: combine bit fields
let toggled: u8 = flags ^ 0x80; // EOR: toggle bit 7
let inverted: u8 = ~value; // EOR #$FF: flip all bits
Common idioms:
let low_nibble = value & 0x0F; // Extract low 4 bits
let is_set = flags & 0x80; // Test bit 7
let wrapped = index & 0xFF; // Modulo 256 (faster than mod8())
let aligned = addr & 0xFFF0; // Align to 16-byte boundary
flags = flags | 0x01; // Set bit 0
flags = flags & ~0x01; // Clear bit 0
flags = flags ^ 0x80; // Toggle bit 7
Comparison Operators
All six comparison operators produce bool results. Mixed-width integer operands are widened as for any binary operator (see Implicit Integer Promotion).
<, <=, > and >= reject a signed operand compared with an unsigned one, such as an i8 with a u8 or a u16. No single comparison is right for both, and -1 < 5 would come out false. Cast one side with as so both have the same signedness. An unsuffixed literal takes the other operand's type, so x < 5 and x < -1 need no cast.
| Operator | Meaning | Unsigned Cycles | Signed Cycles |
|---|---|---|---|
== | Equal | 4--6 | 4--6 |
!= | Not equal | 4--6 | 4--6 |
< | Less than | 4--6 | 8--15 |
> | Greater than | 4--6 | 8--15 |
<= | Less than or equal | 4--6 | 8--15 |
>= | Greater than or equal | 4--6 | 8--15 |
Unsigned comparisons use CMP followed by a branch on carry (BCC/BCS). Signed comparisons require additional logic to handle the overflow flag, which makes them significantly more expensive.
if x == 0 { } // CMP #0; BNE skip
if x < 100 { } // CMP #100; BCS skip (unsigned)
if (x: i8) < 0 { } // Signed comparison (more complex codegen)
Logical Operators
&&, ||, and ! require bool operands and produce bool results.
&& and || use short-circuit evaluation: the right operand is not evaluated if the left operand determines the result.
if a > 0 && b < 100 {
// b < 100 is only evaluated if a > 0 is true
}
if ready || timeout {
// timeout is only evaluated if ready is false
}
let inverted: bool = !flag; // EOR #$01 (flips bit 0)
Unary Operators
Unary Minus
-expr performs two's complement negation. The result type matches the operand type.
let neg: i8 = -value;
// Compiles to: EOR #$FF; INC A (4-6 cycles)
Negating zero produces zero. Negating the minimum signed value (-128 for i8) wraps back to itself.
Bitwise NOT
~expr flips all bits. The result type matches the operand type.
let inv: u8 = ~value;
// Compiles to: EOR #$FF (2-4 cycles)
let inv16: u16 = ~value16;
// Compiles to: EOR #$FFFF (2-4 cycles)
Compound Assignment
All arithmetic and bitwise operators support compound assignment forms. On primitive types these behave like a = a op b and inherit the restrictions of the base operator. A struct can support them too by implementing the matching operator trait — see Operator Overloading.
a += 5; // a = a + 5
a -= 1; // a = a - 1
a &= 0x0F; // a = a & 0x0F
a |= 0x80; // a = a | 0x80
a ^= mask; // a = a ^ mask
a <<= 3; // a = a << 3 (constant required)
a >>= 1; // a = a >> 1 (constant required)
a *= 2; // a = a * 2 (power of 2, 1–256)
a /= 4; // a = a / 4 (power of 2, 1–256)
a *= b; // COMPILE ERROR: variable multiply
a /= b; // COMPILE ERROR: variable divide
a %= b; // COMPILE ERROR outside a const fn
The compiler generates optimized memory operations where possible:
A += 1; // INC A (2 cycles)
COUNTER += 1; // INC COUNTER (5-6 cycles)
Increment and Decrement
x++ and x-- are postfix-only, statement-only operators. They cannot be used inside expressions.
counter++; // Desugars to: counter += 1
counter--; // Desugars to: counter -= 1
Hardware registers compile to single-instruction forms:
X++; // INX (2 cycles)
Y++; // INY (2 cycles)
A++; // INC A (2 cycles)
X--; // DEX (2 cycles)
Y--; // DEY (2 cycles)
A--; // DEC A (2 cycles)
These operators work with any lvalue: variables, registers, array elements, and struct fields.
buffer[i]++;
player.health--;
There is no prefix form (++x, --x). Since increment and decrement are statement-only and do not return values, the prefix form would be redundant.
String Concatenation
When the + operator has a string literal as either operand, it performs compile-time string concatenation instead of arithmetic. This only works in static initializers (constant expressions).
static mut HELLO: [u8; 16] = "Hello, " + "World"; // "Hello, World"
static mut COUNT: [u8; 16] = "Count: " + 42; // "Count: 42"
static mut ABC: [u8; 16] = "A" + "B" + "C"; // "ABC"
String concatenation has zero runtime cost.
Type Casts
The as keyword performs explicit type conversions. No implicit conversions occur in R65, except integer promotion in binary expressions and a fieldless enum used as an integer of its width. The full table of casts, their behavior and their cost is in Types — Type Conversions.
Examples
// Zero-extend: u8 to u16
let wide: u16 = (narrow as u16) + offset;
// Sign-extend: i8 to i16
let signed_wide: i16 = (signed_byte as i16);
// Truncate: u16 to u8
let low_byte: u8 = word as u8;
// Reinterpret: unsigned to signed (no code generated)
let signed: i8 = unsigned_val as i8;
// Pointer cast
let byte_ptr: *u8 = word_ptr as *u8;
let addr: u16 = ptr as u16;
// Enum to integer
let dir_value: u8 = Direction::North as u8;
Operator Precedence
Operators are listed from highest precedence (evaluated first) to lowest. Operators at the same precedence level associate left to right, except assignment operators which associate right to left.
| Precedence | Category | Operators |
|---|---|---|
| 1 (highest) | Unary | - (negate), ~, !, * (deref), & (address-of) |
| 2 | Cast | as |
| 3 | Multiplicative | *, / |
| 4 | Additive | +, - |
| 5 | Shift | <<, >> |
| 6 | Bitwise AND | & |
| 7 | Bitwise XOR | ^ |
| 8 | Bitwise OR | | |
| 9 | Comparison | <, <=, >, >= |
| 10 | Equality | ==, != |
| 11 | Logical AND | && |
| 12 | Logical OR | || |
| 13 (lowest) | Assignment | =, +=, -=, *=, /=, &=, |=, ^=, <<=, >>= |
As in Rust, the bitwise operators bind tighter than comparisons, so flags & 0x80 != 0 means (flags & 0x80) != 0. Function calls, indexing and field access bind tighter than any operator.
Use parentheses to override precedence:
let x = (a + b) * 2; // Addition first, then multiply
let y = a & (b | c); // OR first, then AND
let z = (flags & 0x80) != 0; // Same as flags & 0x80 != 0; the parentheses are for the reader
Software Functions for Expensive Operations
When an operation cannot be expressed with the restricted operators, call the corresponding function from the standard library's math.r65 (include!("lib/math.r65")). They are ordinary (far) functions; the Math Library page has the full signatures.
Summary
| Function | Signature | Cost |
|---|---|---|
mul8 | (a @ A: u8, b @ B: u8) -> u16 — full 16-bit product | ~8 cycles (SNES hardware), ~150--300 (software) |
mul16 | (a @ A: u16, b: u16) -> u16 — low 16 bits | ~8 cycles (SNES hardware), ~150--300 (software) |
div8 / mod8 | (dividend @ A: u8, divisor @ X: u16) -> u8 | ~30 cycles (SNES hardware), ~200--400 (div8 in software) |
div16 / mod16 | (dividend @ A: u16, divisor: u8) -> u16 | ~30 cycles (SNES hardware) |
shl8 / shr8 / shri8 | (value @ A: u8, amount @ X: u16) -> u8 | grows linearly with amount |
shl16 / shr16 | (value @ A: u16, amount @ X: u16) -> u16 | grows linearly with amount |
div16, mod16 and mod8 exist only in SNES builds (--cfg snes), where the hardware math units are available; a non-SNES build uses mod_shift for modulo.
mul8() / mul16()
General-purpose multiplication. mul8 returns the full 16-bit product of two bytes; mul16 returns the low 16 bits.
let area: u16 = mul8(width, height);
let offset: u16 = mul16(y as u16, 320);
div8() / div16()
General-purpose division. Division by zero is undefined behavior.
let avg: u8 = div8(sum, count as u16);
let tiles: u8 = div8(pixels, 7);
mod8()
Returns the remainder after division. Division by zero is undefined behavior.
let remainder: u8 = mod8(distance, tile_size as u16);
// Prefer bitwise AND for power-of-2 modulo:
let wrapped: u8 = index & 0x0F; // Same as mod8(index, 16), much faster
shl8() / shl16() and shr8() / shr16()
Variable shift amounts. The amount is passed in X as a u16 and can be a runtime value.
let shifted: u8 = shl8(value, bit_pos); // Variable left shift
let extracted: u8 = shr8(flags, offset); // Variable right shift
shr8() / shr16() perform a logical right shift (fills with zeros); shri8() performs an arithmetic right shift that preserves the sign bit.
If the shift amount is a compile-time constant, prefer the << and >> operators. They compile to inline instructions and avoid the subroutine call overhead.
Fast vs. Slow: Choosing the Right Operation
// FAST: operator compiles to 1-3 instructions
let doubled: u8 = value * 2; // ASL (2 cycles)
let halved: u8 = value / 2; // LSR (2 cycles)
let shifted: u8 = value << 5; // 5x ASL (10 cycles)
let masked: u8 = value & 0x1F; // AND #$1F (2-4 cycles)
// SLOWER: function compiles to a subroutine call (see the costs above)
let product: u16 = mul8(value, 7);
let quotient: u8 = div8(value, 3);
let remainder: u8 = mod8(value, 5); // SNES builds only
let shifted: u8 = shl8(value, amount);
Guidelines:
- Use operators whenever possible -- they are always faster than function equivalents.
- Use
a * 2/a * 4/a * 8instead ofmul8(a, 2)/mul8(a, 4)/mul8(a, 8). - Use
a & maskinstead ofmod8(a, power_of_2)for power-of-2 modulo. - Avoid
div8()andmod8()in tight loops. Pre-compute values or use lookup tables. - Favor 8-bit operations over 16-bit when possible -- they are faster in m8 mode.
- Use
a += 1ora++instead ofa = a + 1-- the compiler emitsINC/INX/INY.
Overflow and Wrapping
All operations wrap silently. There are no overflow traps, checked arithmetic, or saturating operations.
let x: u8 = 255 + 1; // 0 (wraps)
let y: u8 = 0 - 1; // 255 (wraps)
let z: i8 = 127 + 1; // -128 (wraps)
Division by zero is undefined behavior at runtime. Constant division by zero is caught at compile time.
let x: u8 = div8(10, 0); // Undefined behavior (no runtime check)
let y: u8 = 10 / 0; // Compile error (constant expression)