Last time our processor learned to put a number into register A and stop. But it cannot do anything with that number, not even add one. Today it learns to count, and in the process we meet the first real surprise of both the 6502 and Rust.
By the end of this part
- Your processor has a second register, X, and can count with it.
- You know what a byte does when it runs out of room, and how to tell Rust you want that.
- The loose variables are gathered into one
Cpuvalue with its own functions.
Two new opcodes
If you did the exercises from Part 1, you have already written this. If not, here it is. The 6502 has a second register called X, and two short opcodes that use it:
AA TAX copy A into X
E8 INX add one to XNeither needs a second byte. In our program from Part 1 that means one more variable and two more lines in the match:
let mut a: u8 = 0;
let mut x: u8 = 0;
let mut pc = 0; ...
match opcode {
0xA9 => {
// LDA: load the next byte into A
a = program[pc];
pc += 1;
}
0xAA => x = a, // TAX: copy A into X
0xE8 => x = x + 1, // INX: add one to X
0x00 => break, // BRK: stop
_ => panic!("unknown opcode ${:02X}", opcode),
}Try it on a program that loads 5, copies it to X, and adds one twice: A9 05 AA E8 E8 00.
$ cargo run -q
A = $05 X = $07
Five, six, seven. It counts. Now the experiment from the end of Part 1: start from $FE instead of $05, so the program is A9 FE AA E8 E8 00. What do you expect in X?
$ cargo run -q
thread 'main' (4102523) panicked at src/main.rs:21:25:
attempt to add with overflow
We did not write that message. Rust did. (Your line number may differ a little from mine.)
When a byte runs out of room
$FE plus one is $FF, which is 255, the biggest number a byte can hold. All eight switches are on. Adding one more would give 256, and 256 needs a ninth switch that does not exist.
This situation has a name: overflow. What is overflow? Overflow is what happens when the result of a calculation is too big for the place that has to hold it.
A real 6502 does exactly what the picture shows. The ninth bit falls off the end and X becomes $00. Nobody is told. Counting that goes round like this is called wrapping.
Rust takes a different view. An overflow you did not plan for is usually a bug, so while you are developing, Rust stops the program rather than hand you a wrong number. When wrapping is what you want, you say so:
0xE8 => x = x.wrapping_add(1), // INX: add one to X
wrapping_add means "add, and if it does not fit, wrap round like the hardware would". Notice the shape: x.wrapping_add(1). In Rust even a plain number has functions attached to it, called with a dot.
Here is the whole run with that fix in. Step through it and watch X at step 5.
match opcode {
0xA9 => {
a = program[pc];
pc += 1;
}
0xAA => x = a,
0xE8 => x = x.wrapping_add(1),
0x00 => break,
}- The start. Both registers hold 0 and
pcis at the first byte. A9 FEis LDA, as in Part 1. A becomes FE andpchas moved past both bytes.AAis TAX: copy A into X. X becomes FE. A keeps its value; a copy does not empty the source.E8is INX: add one to X. X becomes FF, the biggest value a byte can hold.E8again. FF plus one does not fit in a byte, so it wraps. X becomes 00.00is BRK. We stop with A = FE and X = 00.
Too many loose variables
The program works, but look at what is piling up at the top of main: a, x, pc. Soon there will be more. These variables are not independent things; together they are the processor. Rust lets us say so.
Cpu holds all of it.The box on the right is a struct. What is a struct? A struct is a type you define yourself: a bundle of named values, called fields, that travel together.
And the loop that works on those fields can be attached to the struct, so that we can write cpu.run(...). A function attached to a type like this is called a method. What is a method? A method is a function that belongs to a type and is called on a value of that type with a dot. You have already used one: wrapping_add is a method of u8.
Here is the whole file, rewritten around a Cpu struct. The behaviour is the same as before; only the organisation is new.
struct Cpu {
a: u8,
x: u8,
pc: usize,
}
impl Cpu {
fn new() -> Cpu {
Cpu { a: 0, x: 0, pc: 0 }
}
fn run(&mut self, program: &[u8]) {
loop {
let opcode = program[self.pc];
self.pc += 1;
match opcode {
0xA9 => {
// LDA: load the next byte into A
self.a = program[self.pc];
self.pc += 1;
}
0xAA => self.x = self.a, // TAX: copy A into X
0xE8 => self.x = self.x.wrapping_add(1), // INX: add one to X
0x00 => break, // BRK: stop
_ => panic!("unknown opcode ${:02X}", opcode),
}
}
}
}
fn main() {
let program: [u8; 6] = [0xA9, 0xFE, 0xAA, 0xE8, 0xE8, 0x00];
let mut cpu = Cpu::new();
cpu.run(&program);
println!("A = ${:02X} X = ${:02X}", cpu.a, cpu.x);
}The new Rust, from the top:
struct Cpu { … }lists the fields and their types. It describes what a Cpu is; it does not create one.impl Cpu { … }holds the functions that belong to Cpu ("impl" is short for implementation).fn new() -> Cpu: the arrow gives the type of value the function hands back. Its body isCpu { a: 0, x: 0, pc: 0 }, which builds a Cpu with those field values. There is noreturnand no semicolon: in Rust, the last expression in a function is what it returns.fn run(&mut self, …):selfis the Cpu the method was called on, so inside it we writeself.a,self.pc. The&mutin front says "I need to change it".program: &[u8]means "some bytes, any number of them, that belong to someone else and that I only want to look at". That is whymainpasses&program. The&sign gets a proper explanation in Part 6; until then, read it as "lend".Cpu::new(): two colons call a function that belongs to the type itself rather than to one particular Cpu.
Run it:
$ cargo run -q
A = $FE X = $00
Shortcuts we took on purpose
pcis still just a position in a Rust array. On the real machine it is an address in memory. Fixed in Part 3.- On a real 6502,
INXandTAXalso leave a note about their result for later instructions to read. Fixed in Part 4. - We use
&without really explaining it. Fixed in Part 6.
What changed today
- The processor has a second register, X, and knows
TAX($AA) andINX($E8). - Adding one to
$FFwraps to$00, because we asked for it withwrapping_add. - The registers and
pclive in astruct Cpu; the loop is itsrunmethod.
Now you
- Add
$CA, nicknamedDEX: "subtract one from X". Before you runA9 00 AA CA 00, predict what X will be.Hint
u8has awrapping_submethod too. Going down from zero wraps the other way. - The 6502 has a third register, Y. Add a field for it and the opcodes
$A8(TAY, copy A into Y) and$C8(INY, add one to Y). How many places in the file did you have to touch? - Our processor forgets everything the moment the program ends, and it can only hold as many values as it has registers. Give the
Cpua fieldmemory: [u8; 16], starting as[0; 16], and invent an opcode:8D nmeans "store A intomemory[n]". Print the memory at the end. Part 3 does this for real, with 65,536 slots instead of 16.Hint
To use au8as an array position, Rust wants you to convert it:memory[n as usize]. Part 3 explains why. To print a whole array, use{:?}as the hole. - Write today's file again from blank, without looking. If you get stuck on the struct syntax, that is the part to practise.
Check your understanding
- What is overflow?
Answer
What happens when the result of a calculation is too big for the place that has to hold it. - What does a real 6502 do on overflow, and what does Rust do by default?
Answer
The 6502 wraps round silently. Rust stops the program with a panic, unless you ask for wrapping with a method such aswrapping_add. - What is a struct?
Answer
A type you define yourself: a bundle of named fields that travel together. - What is a method?
Answer
A function that belongs to a type and is called on a value of that type with a dot. - Inside a method, what is
self?Answer
The particular value the method was called on. Incpu.run(…),selfiscpu.
Next time
Right now our processor has two bytes of storage and forgets them when it stops. A real NES has 65,536 numbered slots of memory, and the program itself lives in them. In Part 3 we give the Cpu a memory and teach it to store things there.