071. 指令 inc

添加 INC 指令原语。

71 / 356 · tests/chapter_01_cpu/test_071_instruction_inc.py

在本步骤中,只添加 emulator/cpu/instructions.py:inc。操作码导入、处理函数和表条目属于第 072-075 课。

本步骤存在的原因

INC 是一个内存读-改-写操作。将运算逻辑保留在单一指令原语中,可以让后续各个寻址模式处理函数只负责解析地址,再委托给相同的变更和标志位行为。

emulator/cpu/instructions.py 中的建议实现,插入到 sbc 之后:

def inc(cpu: CPU, address: int):
    value = cpu.bus.read(address)
    result = value + 1
    result_8 = result & 0xFF

    # Set flags
    cpu.flags.set_negative_flag((result_8 & 0b1000_0000) != 0)
    cpu.flags.set_zero_flag(result_8 == 0)

    # Set value on address
    cpu.bus.write(address, result_8)

不变量:address 是一个有效地址,而不是操作数值;字节通过 cpu.bus 进行读取和写入;掩码运算提供 8 位环绕;Zero 和 Negative 反映掩码后的结果;Carry、Overflow 以及 A/X/Y 保持不变。

常见误解:不要递增 A,也不要把 cpu.bus.read(address) 传给 inc。INC 自己负责内存的读取,并把结果写回同一地址。

范围之外:操作码接线不属于第 071 步;零页到绝对-X 的集成将在第 072-075 课中进行。

运行本课

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