tuanp.dev

Part 2 of 20 · about an hour

A CPU that can count

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 Cpu value 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 X

Neither needs a second byte. In our program from Part 1 that means one more variable and two more lines in the match:

src/main.rs, first attemptSnapshot
    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.

Eight bits all set to 1, which is FF. After adding one, all eight bits are 0, and a ninth bit holding 1 falls off the left edge because there is no room for it.11111111add one000000001no room: lost$FF$00
Like a car's mileage counter rolling from 99999 to 00000. The carry has nowhere to go, so what is left is zero.

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.

The pc arrow walks along the six program bytes A9, FE, AA, E8, E8, 00. Register A becomes FE. Register X becomes FE, then FF, then wraps to 00.012345A9FEAAE8E800pcA00X00
match opcode {
    0xA9 => {
        a = program[pc];
        pc += 1;
    }
    0xAA => x = a,
    0xE8 => x = x.wrapping_add(1),
    0x00 => break,
}
  1. The start. Both registers hold 0 and pc is at the first byte.
  2. A9 FE is LDA, as in Part 1. A becomes FE and pc has moved past both bytes.
  3. AA is TAX: copy A into X. X becomes FE. A keeps its value; a copy does not empty the source.
  4. E8 is INX: add one to X. X becomes FF, the biggest value a byte can hold.
  5. E8 again. FF plus one does not fit in a byte, so it wraps. X becomes 00.
  6. 00 is 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.

On the left, three separate boxes labelled a, x and pc. A fat arrow points to the right, where the same three boxes sit inside one larger box labelled Cpu.aFEx00pc6CpuaFEx00pc6
Same three values, now one thing with a name. Whoever holds the 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.

src/main.rsSnapshot
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 is Cpu { a: 0, x: 0, pc: 0 }, which builds a Cpu with those field values. There is no return and no semicolon: in Rust, the last expression in a function is what it returns.
  • fn run(&mut self, …): self is the Cpu the method was called on, so inside it we write self.a, self.pc. The &mut in 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 why main passes &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

  • pc is 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, INX and TAX also 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) and INX ($E8).
  • Adding one to $FF wraps to $00, because we asked for it with wrapping_add.
  • The registers and pc live in a struct Cpu; the loop is its run method.

Now you

  1. Add $CA, nicknamed DEX: "subtract one from X". Before you run A9 00 AA CA 00, predict what X will be.
    Hintu8 has a wrapping_sub method too. Going down from zero wraps the other way.
  2. 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?
  3. Our processor forgets everything the moment the program ends, and it can only hold as many values as it has registers. Give the Cpu a field memory: [u8; 16], starting as [0; 16], and invent an opcode: 8D n means "store A into memory[n]". Print the memory at the end. Part 3 does this for real, with 65,536 slots instead of 16.
    HintTo use a u8 as 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.
  4. 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

  1. What is overflow?
    AnswerWhat happens when the result of a calculation is too big for the place that has to hold it.
  2. What does a real 6502 do on overflow, and what does Rust do by default?
    AnswerThe 6502 wraps round silently. Rust stops the program with a panic, unless you ask for wrapping with a method such as wrapping_add.
  3. What is a struct?
    AnswerA type you define yourself: a bundle of named fields that travel together.
  4. What is a method?
    AnswerA function that belongs to a type and is called on a value of that type with a dot.
  5. Inside a method, what is self?
    AnswerThe particular value the method was called on. In cpu.run(…), self is cpu.

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.