015. Lda 零页寻址

添加零页寻址的 LDA($A5)。

15 / 356 · tests/chapter_01_cpu/test_015_LDA_zero_page.py

要更新的文件

emulator/cpu/addressing_modes.py
emulator/cpu/cpu.py

位置

addressing_modes.absolute, changed from returning a value to an address
addressing_modes.zero_page
CPU.step, updated $AD branch and new $A5 branch

为什么需要这一步

零页寻址用一个操作数字节编码地址。本课还确立了一条可复用的规则:内存寻址模式返回地址;操作码代码在调用指令之前执行最后的总线读取。

完整示例实现

# emulator/cpu/addressing_modes.py
def absolute(cpu) -> int:
    return cpu.fetch_word()


def zero_page(cpu) -> int:
    return cpu.fetch_byte()


# emulator/cpu/cpu.py
from emulator.cpu.addressing_modes import zero_page
from emulator.cpu.instructions import lda


class CPU:
    def step(self) -> None:
        opcode = self.fetch_byte()

        if opcode == 0xA5:
            address = zero_page(self)
            value = self.bus.read(address)
            lda(self, value)
            return

        if opcode == 0xAD:
            address = absolute(self)
            value = self.bus.read(address)
            lda(self, value)
            return

重要不变量

  • zero_page 恰好消耗一个操作数字节
  • zero_page 和 absolute 现在返回地址
  • CPU.step 执行最后的总线读取
  • lda 仍负责 A 和 Z/N

常见误解

操作数 $10 表示地址 $0010,而不是值 $10,也不是相对于当前程序计数器的地址。

范围之外

  • 操作码表分发,在测试 016 中引入
  • 零页变址寻址的回绕
  • 周期时序

运行本课

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