203. Instruction tsx

implement the TSX operation.

Lesson 203 of 356 · tests/chapter_01_cpu/test_203_instruction_tsx.py

Why this step exists

In this step, add `emulator/cpu/instructions.py::tsx`. TSX complements step 201 by copying the stack-pointer byte into X and deriving the two result flags from the copied value.

Suggested implementation

def tsx(cpu: CPU):
    cpu.x = cpu.s
    cpu.flags.set_zero_flag(cpu.x == 0)
    cpu.flags.set_negative_flag((cpu.x & 0b1000_0000) != 0)

Invariants: S, A, Y, PC, memory, and status bits other than Zero and Negative are unchanged. Zero is set exactly for $00; Negative follows bit 7, not bit 6. The common misconception is to treat TSX like TXS and preserve every flag, or to calculate flags from X before copying S.

Out of scope: importing TSX and mapping implied opcode $BA in `emulator/cpu/opcodes.py` belongs to step 204; no other stack API is added.

Run this lesson

uv run pytest tests/chapter_01_cpu/test_203_instruction_tsx.py -v