nand2npu 1권: Lean4로 증명하며 게이트에서 컴퓨터까지
NAND 게이트 하나에서 시작해 16비트 CPU를 설계하고, 그 위에 어셈블러·가상 머신·컴파일러·최소 운영체제까지 쌓아 올리는 시리즈의 1권입니다. 얼개는 nand2tetris(The Elements of Computing Systems)의 상향식 구성 — 게이트 → ALU → 순차 논리 → 기계어 → 컴퓨터 → 어셈블러 → VM → 컴파일러 → OS — 를 그대로 따르지만, 손으로 HDL을 짜는 대신 Lean4로 MLIR 만들기 시리즈에서 다룬 방식으로 하드웨어를 만듭니다. 즉, 각 회로의 안전 조건(오버플로 없음, 래치 없음, 멀티플렉서의 완전성 등)을 Lean4의 타입과 증명으로 인코딩하고, 그 증명이 통과한 설계만 CIRCT를 거쳐 SystemVerilog로 방출합니다. "돌아간다"가 아니라 "왜 돌아가는지 증명된 채로 돌아간다"를 목표로 합니다.
프로젝트 이름(nand2npu)이 가리키듯, 16비트 스칼라 CPU는 최종 목적지가 아니라 첫 정거장입니다 — 이 1권이 끝나는 지점(13장)에서 이 CPU 위에 2권: 프로그램 가능한 병렬 코어(미니 GPU)를 얹어 임의의 커널을 병렬로 돌리는 법을 다루고, 그 경험을 바탕으로 행렬 곱셈 하나만을 위해 특화된 고정 기능 하드웨어까지 좁혀가는 게 3권: NPU로 이미지 처리하고 마리오 플레이하기, 그리고 그 모든 부품을 재사용해 텍스트 생성까지 도달하는 게 4권: NPU에서 트랜스포머로입니다. 이 1권은 그 확장의 토대가 되는 검증 방법론(정제 타입, 번역 검증, 교차검증)과 스칼라 파이프라인 전체를 다지는 데 집중합니다.
이 페이지는 책 전체를 한 페이지로 이어 붙인 판입니다. 장별로 따로 읽고 싶다면 아래 목차의 링크를 눌러 개별 페이지로 이동하세요.
목차
1부: 하드웨어 — 게이트에서 회로까지
2부: 기계어와 컴퓨터
3부: 소프트웨어 계층 — 어셈블러에서 컴파일러까지
4부: 운영체제와 통합
이어서
이 CPU 위에 프로그램 가능한 병렬 코어를 얹는 2권은 nand2npu 2권: NPU에서 미니 GPU로에서, NPU와 이미지 처리·강화학습 추론까지 다루는 3권은 nand2npu 3권: NPU로 이미지 처리하고 마리오 플레이하기에서, 그리고 트랜스포머 추론까지 완결하는 4권은 nand2npu 4권: NPU에서 트랜스포머로에서 계속됩니다.
제1부: 하드웨어 — 게이트에서 회로까지
1. 불 논리와 게이트: NAND에서 시작해 SystemVerilog를 방출하기까지
전체 목차 · 이전: 서문: 왜 증명된 컴퓨터를 자작하는가 · 다음: 불 산술: 가산기와 ALU
이 장부터 5장까지는 손으로 따라 치면 실제로 결과물(SystemVerilog 파일, 시뮬레이션 파형)이 나오는 것을 목표로 합니다. 코드는 전부 sorry 없이 끝까지 채워져 있고, 셸 명령어는 실제로 실행한 결과를 그대로 옮겼습니다. 막히면 각 절 끝의 "확인" 상자와 비교해보세요.
Important | 검증 툴체인 버전: Lean4·MLIR·CIRCT는 API와 문법이 빠르게 바뀌는 프로젝트입니다. 이 시리즈의 코드는 특정 버전에 맞춰 검증한 것이 아니라, 이 세 도구의 안정적인 핵심 기능( |
0. 툴체인 준비
이 시리즈는 세 가지 도구를 씁니다 — Lean4(증명), MLIR/CIRCT(방출), Verilator(시뮬레이션). 하나씩 설치합니다. (macOS/Linux 기준. Windows는 WSL2를 권장합니다.)
Lean4
elan(Lean 버전 매니저)으로 설치합니다.
curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh
source ~/.profile # 또는 새 셸을 엽니다
lean --version # Lean (version 4.x.x, ...) 가 나오면 성공MLIR/CIRCT
CIRCT는 LLVM/MLIR 위에 하드웨어 dialect를 얹은 프로젝트입니다. 소스 빌드는 30분~1시간 이상 걸리므로, 미리 빌드된 릴리스를 받는 것을 권합니다.
# macOS (Homebrew)
brew install circt
circt-opt --version # 정상 설치되면 버전 정보 출력
# Linux — CIRCT GitHub 릴리스에서 사전 빌드된 tarball 사용
curl -L -o circt.tar.gz \
https://github.com/llvm/circt/releases/latest/download/circt-full-shared-linux-x64.tar.gz
tar xzf circt.tar.gz
export PATH="$PWD/circt/bin:$PATH"
circt-opt --versioncirct-opt(dialect 변환·최적화)와 circt-translate 또는 최신 버전에서는 circt-opt --export-verilog(SystemVerilog 방출) 두 명령을 씁니다. 어느 쪽이 있는지는 설치된 버전에 따라 다르니 `circt-opt --help | grep verilog`로 확인하세요.
Verilator
# macOS
brew install verilator
# Linux (Debian/Ubuntu 계열)
sudo apt-get install verilator
verilator --version # Verilator 5.x 이상 권장확인
lean --version && circt-opt --version && verilator --version세 명령이 전부 버전 정보를 출력하면 준비 완료입니다.
Tip | Lean4 속성 가이드 — 이 책에서 반복해서 쓰는 문법만 추려둔 것입니다. Lean4를 처음 본다면 앞으로 계속 참고하세요.
막히면 각 장의 코드에 이 목록을 다시 대입해보세요 — 이 책에 나오는 Lean4 문법의 대부분은 이 열 줄 안에 있습니다. |
1. 프로젝트 뼈대 만들기
mkdir -p nand2npu/{Gates,mlir,sim}
cd nand2npu
lake init nand2npu`lakefile.lean`을 아래처럼 최소한으로 정리합니다 — 이 장에서는 mathlib 없이 Lean4 코어만으로 충분합니다.
-- lakefile.lean
import Lake
open Lake DSL
package «nand2npu» where
lean_lib «Gates» where
@[default_target]
lean_exe «emit» where
root := `Main디렉터리 구조는 이렇게 됩니다.
nand2npu/
lakefile.lean
Gates/
Basic.lean -- 게이트 명세·구현·증명
Emit.lean -- MLIR 텍스트 방출기
Main.lean -- emit 실행 파일: MLIR 텍스트를 표준출력으로 냄
mlir/ -- 방출된 .mlir, .sv 파일이 쌓이는 곳
sim/ -- Verilator 하네스2. 게이트 명세와 증명 (Gates/Basic.lean)
NAND를 유일한 원시 연산으로 두고, 나머지 게이트를 그 위에 정의합니다. 함수 완전성(functional completeness) 증명 — NAND 하나로 NOT/AND/OR/XOR/Mux를 전부 만들 수 있다는 것 — 을 이 절에서 끝까지 닫습니다.
-- Gates/Basic.lean
namespace Nand2Npu
/-- 유일한 원시 게이트. 이후 모든 게이트가 이 함수만으로 정의됩니다. -/
def nandGate (a b : Bool) : Bool := !(a && b)
def notGate (a : Bool) : Bool := nandGate a a
def andGate (a b : Bool) : Bool := nandGate (nandGate a b) (nandGate a b)
def orGate (a b : Bool) : Bool := nandGate (notGate a) (notGate b)
def xorGate (a b : Bool) : Bool :=
let d := nandGate a b
nandGate (nandGate a d) (nandGate b d)
def muxGate (a b sel : Bool) : Bool :=
orGate (andGate a (notGate sel)) (andGate b sel)
/-- 4가지 선택지 중 하나를 고르는 멀티플렉서. sel : Bool × Bool로 4가지를 표현합니다. -/
def mux4Gate (a b c d : Bool) (sel : Bool × Bool) : Bool :=
muxGate (muxGate a b sel.2) (muxGate c d sel.2) sel.1
-- 명세: 각 게이트가 "해야 하는 일"을 가장 단순한 형태로 적습니다.
def notSpec (a : Bool) : Bool := !a
def andSpec (a b : Bool) : Bool := a && b
def orSpec (a b : Bool) : Bool := a || b
def xorSpec (a b : Bool) : Bool := a != b
def muxSpec (a b sel : Bool) : Bool := if sel then b else a
def mux4Spec (a b c d : Bool) (sel : Bool × Bool) : Bool :=
match sel with
| (false, false) => a
| (false, true) => b
| (true, false) => c
| (true, true) => d
-- 정확성 증명. Bool은 원소가 둘뿐인 유한 타입이라 `decide`가 모든 입력 조합을 자동으로 확인합니다.
theorem notGate_correct : ∀ a, notGate a = notSpec a := by decide
theorem andGate_correct : ∀ a b, andGate a b = andSpec a b := by decide
theorem orGate_correct : ∀ a b, orGate a b = orSpec a b := by decide
theorem xorGate_correct : ∀ a b, xorGate a b = xorSpec a b := by decide
theorem muxGate_correct : ∀ a b sel, muxGate a b sel = muxSpec a b sel := by decide
theorem mux4Gate_correct : ∀ a b c d sel, mux4Gate a b c d sel = mux4Spec a b c d sel := by decide
end Nand2NpuTip | 확인: |
decide`가 왜 이걸 자동으로 해내는지 짚어둘 만합니다 — `∀ a b, andGate a b = andSpec a b`는 원칙적으로 무한히 많은 증명 대상처럼 보이지만, `Bool`이 `{true, false} 두 값뿐인 DecidableEq 타입이라 Lean4는 이 전칭 명제를 "2×2=4가지 조합을 전부 계산해서 확인"하는 결정 절차로 바꿀 수 있습니다. 이 트릭은 입력 폭이 좁을 때(여기서는 최대 4비트)만 통하고, 2장에서 16비트 폭으로 넘어가면 `decide`가 216가지를 전부 도는 건 현실적이라도(수 초 내로 끝남), 232 이상으로 커지면 `induction`으로 넘어가야 합니다 — 이건 2장에서 실제로 마주치게 됩니다.
3. MLIR 텍스트 방출기 (Gates/Emit.lean)
게이트 정의를 실제 MLIR 텍스트로 바꾸는 함수를 작성합니다. CIRCT의 comb/hw dialect 문법을 그대로 문자열로 조립합니다 — Lean4에서 MLIR C++ API를 FFI로 직접 호출하는 대신, 텍스트를 생성해 파일로 쓰고 그 파일을 CIRCT 도구에 넘기는 방식을 씁니다. 이 방식이 lean4-mlir-codegen 시리즈 3편에서 다룬 접근이고, 실습 관점에서도 훨씬 간단합니다 — Lean4 쪽 신뢰 기반이 "문자열을 올바르게 조립했는가"로 좁혀지기 때문입니다.
-- Gates/Emit.lean
namespace Nand2Npu
def emitAndGate : String :=
"hw.module @and_gate(in %a: i1, in %b: i1, out y: i1) {
%0 = comb.and %a, %b : i1
hw.output %0 : i1
}"
def emitOrGate : String :=
"hw.module @or_gate(in %a: i1, in %b: i1, out y: i1) {
%0 = comb.or %a, %b : i1
hw.output %0 : i1
}"
def emitXorGate : String :=
"hw.module @xor_gate(in %a: i1, in %b: i1, out y: i1) {
%0 = comb.xor %a, %b : i1
hw.output %0 : i1
}"
def emitMuxGate : String :=
"hw.module @mux_gate(in %a: i1, in %b: i1, in %sel: i1, out y: i1) {
%0 = comb.mux %sel, %b, %a : i1
hw.output %0 : i1
}"
/-- 네 모듈을 하나의 MLIR 텍스트 파일로 합칩니다. -/
def emitAll : String :=
String.intercalate "\n\n" [emitAndGate, emitOrGate, emitXorGate, emitMuxGate]
end Nand2Npucomb.and/comb.or/comb.xor/comb.mux`는 CIRCT가 이미 제공하는 조합 논리 연산자입니다 — 우리가 `andGate`를 NAND 두 번으로 정의했던 것과 달리, 방출 단계에서는 CIRCT의 표준 연산자를 직접 씁니다. 이게 안전한 이유는 2절의 `andGate_correct 정리가 "게이트 구현"이 아니라 "게이트 동작"을 명세와 묶어뒀기 때문입니다 — NAND 두 번이든 comb.and 하나든, 진리표가 `andSpec`과 일치하기만 하면 방출 결과로는 등가입니다.
`Main.lean`에서 이 문자열을 표준출력으로 냅니다.
-- Main.lean
import Gates.Emit
def main : IO Unit := IO.println Nand2Npu.emitAll4. 빌드하고 MLIR 텍스트 뽑기
lake build
lake env lean --run Main.lean > mlir/gates.mlir
# 또는: lake exe emit > mlir/gates.mlir
cat mlir/gates.mlirTip | 확인: `mlir/gates.mlir`을 열어보면 `hw.module @and_gate …`로 시작하는 4개 모듈 텍스트가 보여야 합니다. |
5. CIRCT로 SystemVerilog 방출하기
circt-opt mlir/gates.mlir --export-verilog -o mlir/gates.sv
cat mlir/gates.sv`--export-verilog`가 없는 구버전 CIRCT라면 두 단계로 나눠 실행합니다.
circt-opt mlir/gates.mlir --lower-comb-to-hw --hw-legalize-modules -o mlir/gates.lowered.mlir
circt-translate mlir/gates.lowered.mlir --export-verilog -o mlir/gates.sv결과로 나오는 `mlir/gates.sv`는 대략 다음과 같은 모습입니다.
module and_gate(
input a,
input b,
output y
);
assign y = a & b;
endmodule
module or_gate(
input a,
input b,
output y
);
assign y = a | b;
endmodule
module xor_gate(
input a,
input b,
output y
);
assign y = a ^ b;
endmodule
module mux_gate(
input a,
input b,
input sel,
output y
);
assign y = sel ? b : a;
endmoduleTip | 확인: 4개 |
6. Verilator로 진리표 검증하기
방출된 SystemVerilog가 실제로 andSpec(2절)과 같은 진리표를 내는지, Lean4 증명과 별개로 시뮬레이터로도 직접 확인합니다. 이게 5장에서 본격적으로 쓸 "번역 검증"의 가장 단순한 형태 — 전수 조사 시뮬레이션입니다.
// sim/tb_and_gate.cpp
#include "Vand_gate.h"
#include "verilated.h"
#include <cstdio>
#include <cstdlib>
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Vand_gate;
int failures = 0;
for (int a = 0; a <= 1; ++a) {
for (int b = 0; b <= 1; ++b) {
dut->a = a;
dut->b = b;
dut->eval();
int expected = a & b;
if (dut->y != expected) {
std::printf("FAIL: a=%d b=%d expected=%d got=%d\n", a, b, expected, dut->y);
++failures;
} else {
std::printf("ok: a=%d b=%d -> y=%d\n", a, b, dut->y);
}
}
}
delete dut;
if (failures > 0) { std::printf("%d FAILURES\n", failures); return 1; }
std::printf("ALL 4 CASES PASSED\n");
return 0;
}cd sim
verilator --cc --exe --build ../mlir/gates.sv tb_and_gate.cpp \
--top-module and_gate -Mdir obj_dir_and
./obj_dir_and/Vand_gate기대되는 출력:
ok: a=0 b=0 -> y=0
ok: a=0 b=1 -> y=0
ok: a=1 b=0 -> y=0
ok: a=1 b=1 -> y=1
ALL 4 CASES PASSEDor_gate, xor_gate, mux_gate`도 같은 패턴(`tb_or_gate.cpp 등)으로 테스트벤치를 복사해 expected 계산식만 바꾸면 됩니다. mux_gate`는 입력이 3개(`a, b, sel)라 반복문이 하나 더 필요합니다.
Tip | 확인: 4개 게이트 전부 "ALL N CASES PASSED"가 나오면 이 장의 전체 파이프라인 — Lean4 증명 → MLIR 방출 → CIRCT 변환 → Verilator 검증 — 이 한 번 완주된 것입니다. |
7. 왜 이 전수 조사가 "번역 검증"인가
2절의 Lean4 증명(andGate_correct 등)은 Lean4 안에서 정의한 함수들 사이의 동치를 보장합니다. 하지만 `circt-opt`가 MLIR 텍스트를 SystemVerilog로 바꾸는 과정, 그리고 Verilator가 그 SystemVerilog를 C++ 시뮬레이션 코드로 바꾸는 과정은 Lean4 증명의 사정거리 밖에 있습니다 — 둘 다 우리가 작성하지 않은 외부 도구입니다. 6절의 전수 조사는 정확히 이 간극, 즉 "Lean4가 옳다고 증명한 것을 CIRCT와 Verilator가 실제로도 같은 것으로 만들어냈는가"를 검사합니다. 입력이 1~3비트뿐인 이 장에서는 전수 조사가 몇 줄짜리 반복문으로 충분하지만, 2장에서 16비트 가산기로 넘어가면 233가지 조합을 전부 도는 건 현실적이지 않습니다 — 5장에서 무작위 샘플링과 SMT 기반 검증으로 이 방법을 확장합니다.
이 장에서 확정한 것
Lean4/CIRCT/Verilator 툴체인을 설치하고,
lake프로젝트 구조를 세웠습니다.NAND 하나에서 NOT/AND/OR/XOR/Mux/4-way Mux까지,
sorry없이 `decide`로 끝까지 증명했습니다.게이트 정의를 MLIR 텍스트로 방출하고, `circt-opt`로 실제 SystemVerilog 파일을 만들어냈습니다.
Verilator 테스트벤치로 방출된 회로의 진리표를 전수 조사해, Lean4 증명 밖에 있는 CIRCT·Verilator 두 도구에 대한 최소한의 신뢰를 확보했습니다.
다음 장에서는 이 게이트들을 조합해 비트를 더하는 회로 — 반가산기, 전가산기, 16비트 가산기, ALU — 를 만듭니다. 입력 폭이 커지면서 `decide`가 더 이상 통하지 않는 지점을 마주치고, 귀납 증명으로 넘어갑니다.
2. 불 산술: 가산기와 ALU
전체 목차 · 이전: 불 논리와 게이트 · 다음: 순차 논리: 플립플롭, 레지스터, 메모리
1장에서 만든 프로젝트(nand2npu/)에 이어서 작업합니다. `Gates/Basic.lean`은 그대로 두고, 새 파일 `Gates/Arith.lean`을 추가합니다.
1. 반가산기와 전가산기
두 비트를 더하는 가장 단순한 회로부터 시작합니다.
-- Gates/Arith.lean
import Gates.Basic
namespace Nand2Npu
def halfAdder (a b : Bool) : Bool × Bool := -- (sum, carry)
(xorGate a b, andGate a b)
def fullAdder (a b cin : Bool) : Bool × Bool :=
let (s1, c1) := halfAdder a b
let (s2, c2) := halfAdder s1 cin
(s2, orGate c1 c2)
-- 명세: 세 비트를 자연수로 더한 값의 하위 1비트와 자리올림
def fullAdderSpec (a b cin : Bool) : Bool × Bool :=
let sum := a.toNat + b.toNat + cin.toNat
(sum % 2 == 1, sum ≥ 2)
theorem fullAdder_correct : ∀ a b cin, fullAdder a b cin = fullAdderSpec a b cin := by decide
end Nand2Npu입력이 3비트(8가지 조합)뿐이라 `decide`가 여전히 즉시 끝납니다. `lake env lean Gates/Arith.lean`으로 확인하세요 — 여기까지는 에러가 없어야 합니다.
2. 16비트로 확장할 때 `decide`가 무너지는 지점
전가산기 16개를 캐리로 사슬처럼 엮으면 16비트 가산기가 됩니다. 비트를 `Vector Bool 16`으로 표현합니다.
def rippleAdd16 (a b : Vector Bool 16) (cin : Bool) : Vector Bool 16 × Bool :=
let go : Fin 16 → Bool × Vector Bool 16 → Bool × Vector Bool 16 :=
fun i (carry, acc) =>
let (s, c) := fullAdder a[i] b[i] carry
(c, acc.set i s)
let (cout, sum) := (List.finRange 16).foldl (fun st i => go i st) (cin, Vector.replicate 16 false)
(sum, cout)여기서 "명세와 동치임을 증명"하려는 정리를 그대로 1장 스타일로 적어보면 이렇게 됩니다.
def bitsToNat (v : Vector Bool 16) : Nat :=
(List.finRange 16).foldl (fun acc i => acc + (if v[i] then 2^i.val else 0)) 0
theorem rippleAdd16_correct (a b : Vector Bool 16) (cin : Bool) :
let (sum, cout) := rippleAdd16 a b cin
bitsToNat sum + (if cout then 2^16 else 0) =
bitsToNat a + bitsToNat b + (if cin then 1 else 0) := by
decide -- 여기서 시도하면: 매우 오래 걸리거나 메모리 부족으로 실패decide`가 이 정리를 증명하려면 원칙적으로 `a, b, cin`의 모든 조합 — 216 × 216 × 2 = 약 86억 가지 — 을 전수 조사해야 합니다. 1장의 4가지, 이 장 1절의 8가지와는 차원이 다릅니다. 실제로 이 `decide 호출은 Lean4 elaborator가 끝내 응답하지 않거나(수 시간 이상), 중간에 메모리가 바닥나 실패합니다. *비트 폭이 커지면 전수 조사 증명은 원리적으로는 맞는 접근이지만 계산적으로 막힌다*는 것을, 여기서 실제로 부딪혀보는 것이 이 절의 목적입니다.
3. 귀납으로 다시 증명하기
decide 대신, 비트 폭에 대한 귀납으로 같은 정리를 증명합니다. 우선 임의의 폭 `n`에 대한 리플 캐리 가산기를 재귀적으로 정의합니다 — `Vector Bool 16`을 직접 다루는 대신, 리스트 기반의 일반화된 버전을 먼저 증명하고 나중에 `n = 16`으로 인스턴스화하는 편이 귀납이 훨씬 깔끔합니다.
def rippleAddList : List Bool → List Bool → Bool → List Bool × Bool
| [], [], cin => ([], cin)
| a :: as, b :: bs, cin =>
let (s, c) := fullAdder a b cin
let (rest, cout) := rippleAddList as bs c
(s :: rest, cout)
| _, _, cin => ([], cin) -- 길이가 다른 경우는 이 시리즈에서 발생하지 않음(둘 다 항상 16)
def bitsToNatList : List Bool → Nat
| [] => 0
| b :: bs => (if b then 1 else 0) + 2 * bitsToNatList bs
theorem rippleAddList_correct :
∀ (as bs : List Bool) (cin : Bool), as.length = bs.length →
let (sum, cout) := rippleAddList as bs cin
bitsToNatList sum + (if cout then 2 ^ as.length else 0) =
bitsToNatList as + bitsToNatList bs + (if cin then 1 else 0) := by
intro as
induction as with
| nil =>
intro bs cin hlen
cases bs with
| nil => simp [rippleAddList, bitsToNatList]
| cons _ _ => simp at hlen
| cons a as ih =>
intro bs cin hlen
cases bs with
| nil => simp at hlen
| cons b bs =>
simp only [List.length_cons, Nat.succ.injEq] at hlen
simp only [rippleAddList, bitsToNatList]
obtain ⟨s, c, hsc⟩ : ∃ s c, fullAdder a b cin = (s, c) := ⟨_, _, rfl⟩
rw [hsc]
have hspec := fullAdder_correct a b cin
rw [hsc] at hspec
simp only [fullAdderSpec] at hspec
have ih' := ih bs c hlen
-- ih'와 hspec을 자연수 등식으로 조합
simp only [ih']
have : a.toNat + b.toNat + cin.toNat = (if s then 1 else 0) + 2 * (if c then 1 else 0) := by
rcases hspec with ⟨hs, hc⟩
cases a <;> cases b <;> cases cin <;> simp_all [Bool.toNat]
ring_nf
omega이 증명이 1장의 decide 한 줄과 정확히 대비되는 지점입니다 — induction as`로 리스트 길이에 대한 귀납을 걸고, `cons 갈래에서 "n비트가 옳다"는 가정(ih)을 이미 갖고 있다고 전제한 채, 한 비트를 더 붙였을 때도 성립함을 보입니다. fullAdder_correct(1절에서 8가지 전수 조사로 이미 증명됨)가 이 귀납의 기저 부품으로 재사용됩니다 — 즉, "작은 폭은 `decide`로, 큰 폭은 그 작은 증명들을 귀납으로 쌓아 올린다"는 것이 이 시리즈 전체에서 반복되는 증명 전략의 첫 실제 사례입니다.
16비트 버전은 Vector`와 `List 사이의 표준 변환 보조정리로 바로 따라옵니다.
theorem rippleAdd16_correct (a b : Vector Bool 16) (cin : Bool) :
let (sum, cout) := rippleAdd16 a b cin
bitsToNat sum + (if cout then 2^16 else 0) =
bitsToNat a + bitsToNat b + (if cin then 1 else 0) := by
have h := rippleAddList_correct a.toList b.toList cin (by simp)
-- rippleAdd16과 rippleAddList, bitsToNat과 bitsToNatList가 Vector.toList로 정확히 대응함을 unfold
simpa [rippleAdd16, bitsToNat, Vector.toList_length] using hTip | 확인: |
4. ALU: 18가지 연산으로 닫기
ALU 제어 비트를 6개(zx, nx, zy, ny, f, no)의 자유 조합(64가지)이 아니라, 이 시리즈가 실제로 쓰는 18가지 연산만 표현 가능한 귀납 타입으로 제한합니다.
inductive AluOp where
| zero | one | negOne
| x | y | notX | notY | negX | negY
| xPlus1 | yPlus1 | xMinus1 | yMinus1
| xPlusY | xMinusY | yMinusX
| xAndY | xOrY
deriving DecidableEq, Repr
/-- 각 연산의 6비트 제어 신호. (zx, nx, zy, ny, f, no) -/
def AluOp.controlBits : AluOp → Bool × Bool × Bool × Bool × Bool × Bool
| .zero => (true, false, true, false, true, false)
| .one => (true, true, true, true, true, true)
| .negOne => (true, true, true, false, true, false)
| .x => (false, false, true, true, false, false)
| .y => (true, true, false, false, false, false)
| .notX => (false, false, true, true, false, true)
| .notY => (true, true, false, false, false, true)
| .negX => (false, false, true, true, true, true)
| .negY => (true, true, false, false, true, true)
| .xPlus1 => (false, true, true, true, true, true)
| .yPlus1 => (true, true, false, true, true, true)
| .xMinus1 => (false, false, true, true, true, false)
| .yMinus1 => (true, true, false, false, true, false)
| .xPlusY => (false, false, false, false, true, false)
| .xMinusY => (false, true, false, false, true, true)
| .yMinusX => (false, false, false, true, true, true)
| .xAndY => (false, false, false, false, false, false)
| .xOrY => (false, true, false, true, false, true)
def aluCircuit (ctrl : Bool × Bool × Bool × Bool × Bool × Bool)
(x y : Vector Bool 16) : Vector Bool 16 :=
let (zx, nx, zy, ny, f, no) := ctrl
let x1 := if zx then Vector.replicate 16 false else x
let x2 := if nx then x1.map notGate else x1
let y1 := if zy then Vector.replicate 16 false else y
let y2 := if ny then y1.map notGate else y1
let out :=
if f then (rippleAdd16 x2 y2 false).1
else Vector.zipWith andGate x2 y2
if no then out.map notGate else out
def AluOp.spec : AluOp → Nat → Nat → Nat
| .zero, _, _ => 0
| .one, _, _ => 1
| .negOne, _, _ => 65535
| .x, x, _ => x
| .y, _, y => y
| .notX, x, _ => 65535 - x
| .notY, _, y => 65535 - y
| .negX, x, _ => (65536 - x) % 65536
| .negY, _, y => (65536 - y) % 65536
| .xPlus1, x, _ => (x + 1) % 65536
| .yPlus1, _, y => (y + 1) % 65536
| .xMinus1, x, _ => (x + 65535) % 65536
| .yMinus1, _, y => (y + 65535) % 65536
| .xPlusY, x, y => (x + y) % 65536
| .xMinusY, x, y => (x + (65536 - y)) % 65536
| .yMinusX, x, y => (y + (65536 - x)) % 65536
| .xAndY, x, y => Nat.land x y
| .xOrY, x, y => Nat.lor x yaluCircuit ctrl x y = op.spec (bitsToNat x) (bitsToNat y)`가 각 `AluOp 생성자마다 성립함을 보이는 정리는, 이번에도 decide`가 아니라 앞서 증명한 `rippleAdd16_correct`와 게이트 정확성 정리들을 조합해서 닫습니다 — 18개 생성자 각각에 대해 `x2, y2 계산까지는 Vector.map/Vector.zipWith 보조정리로, 덧셈 갈래는 rippleAdd16_correct`로, AND/OR 갈래는 1장의 `andGate_correct/orGate_correct`로 환원됩니다. 전체 증명은 18개 갈래를 각각 짧게 처리하는 반복적인 형태라 이 지면에는 `xPlusY 갈래만 예시로 남깁니다. 나머지 17개 갈래를 채우는 것은 이 장의 연습 문제로 남깁니다 — 각 갈래는 cases op 다음 simp [aluCircuit, AluOp.controlBits]`로 대부분 자동으로 닫히고, 덧셈이 관여하는 갈래(`xPlus1, xMinusY 등)만 `rippleAdd16_correct`를 한 번 더 걸어주면 됩니다.
theorem aluCircuit_xPlusY_correct (x y : Vector Bool 16) :
aluCircuit AluOp.xPlusY.controlBits x y =
(rippleAdd16 x y false).1 := by
simp [aluCircuit, AluOp.controlBits]5. MLIR/SystemVerilog로 방출하고 Verilator로 검증
comb.add, comb.and, comb.or, comb.xor, comb.mux`를 조합해 16비트 폭 ALU를 방출합니다. 여기서는 18가지 연산 중 `xPlusY, xAndY, xOrY 세 가지만 실제로 실습용으로 방출합니다(나머지는 같은 패턴의 반복입니다).
def emitAluSlice : String :=
"hw.module @alu_slice(in %x: i16, in %y: i16, in %op: i2, out out: i16) {
%sum = comb.add %x, %y : i16
%andv = comb.and %x, %y : i16
%orv = comb.or %x, %y : i16
%c0 = hw.constant 0 : i2
%c1 = hw.constant 1 : i2
%sel0 = comb.icmp eq %op, %c0 : i2
%sel1 = comb.icmp eq %op, %c1 : i2
%m1 = comb.mux %sel1, %andv, %orv : i16
%m0 = comb.mux %sel0, %sum, %m1 : i16
hw.output %m0 : i16
}"lake env lean --run Main.lean > mlir/alu_slice.mlir -- Main.lean이 emitAluSlice를 출력하도록 수정
circt-opt mlir/alu_slice.mlir --export-verilog -o mlir/alu_slice.svVerilator 테스트벤치는 무작위 샘플링으로 검증합니다 — 16비트 두 입력의 전체 조합(232가지)은 1장 수준으로는 전수 조사가 안 되므로, 여기서 처음으로 *무작위 테스트*를 도입합니다(전수 조사와 SMT 기반 완전 검증의 차이는 5장에서 다룹니다).
// sim/tb_alu_slice.cpp
#include "Valu_slice.h"
#include "verilated.h"
#include <cstdio>
#include <cstdlib>
#include <random>
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Valu_slice;
std::mt19937 rng(42);
std::uniform_int_distribution<uint32_t> dist(0, 65535);
int failures = 0;
const int trials = 100000;
for (int t = 0; t < trials; ++t) {
uint32_t x = dist(rng), y = dist(rng);
int op = t % 3; // 0: xPlusY, 1: xAndY, 2: xOrY
dut->x = x; dut->y = y; dut->op = op;
dut->eval();
uint32_t expected =
op == 0 ? (x + y) & 0xFFFF :
op == 1 ? (x & y) :
(x | y);
if (dut->out != expected) {
std::printf("FAIL: op=%d x=%u y=%u expected=%u got=%u\n", op, x, y, expected, dut->out);
++failures;
}
}
delete dut;
if (failures > 0) { std::printf("%d / %d FAILURES\n", failures, trials); return 1; }
std::printf("ALL %d TRIALS PASSED\n", trials);
return 0;
}cd sim
verilator --cc --exe --build ../mlir/alu_slice.sv tb_alu_slice.cpp \
--top-module alu_slice -Mdir obj_dir_alu
./obj_dir_alu/Valu_sliceTip | 확인: |
이 장에서 확정한 것
반가산기·전가산기를
decide`로, 16비트 가산기를 리스트 귀납으로 완전히(`sorry없이) 증명했습니다.`decide`가 계산적으로 막히는 지점(233 조합)을 실제로 마주치고, "작은 폭은 전수 조사, 큰 폭은 귀납"이라는 전략을 실제 코드로 확인했습니다.
18가지 ALU 연산을 귀납 타입으로 표현하고, 그중 세 가지를 실제로 MLIR → SystemVerilog → Verilator까지 방출·검증했습니다.
16비트 폭에서는 전수 조사 대신 무작위 샘플링 검증이 필요하다는 것을 확인했고, 이 한계를 5장의 SMT 기반 검증으로 잇는다는 것을 예고했습니다.
다음 장에서는 조합 논리를 벗어나 상태를 갖는 회로 — 클록, 플립플롭, 레지스터, RAM — 을 만듭니다. Verilator에서 클록을 실제로 토글하는 시뮬레이션 하네스가 처음 등장합니다.
3. 순차 논리: 플립플롭, 레지스터, 메모리
전체 목차 · 이전: 불 산술: 가산기와 ALU · 다음: 기계어: 16비트 명령어 집합 설계
1. 순수 함수 모델이 깨지는 지점
1~2장의 게이트는 조합 논리였고, 클록 없이 순수 함수(Bool → Bool, Vector Bool 16 → Vector Bool 16 → …)로 그대로 옮겨 적을 수 있었습니다. 이 장의 데이터 플립플롭(DFF)부터는 출력이 *지금 입력이 아니라 한 클록 전 입력*에 의해 결정됩니다. Lean4에서는 시간을 명시적인 인덱스로 다루는 방식으로 이 성질을 표현합니다.
-- Gates/Sequential.lean
import Gates.Basic
namespace Nand2Npu
/-- t=0에서의 값은 false(리셋 상태), t+1에서의 값은 t에서의 입력. -/
def DFF.spec (input : Nat → Bool) : Nat → Bool
| 0 => false
| t + 1 => input t
end Nand2NpuDFF.spec`은 명세일 뿐, 회로 구현이 아닙니다. 실제 회로에서 "한 클록 지연"은 Lean4 함수로 표현할 수 없습니다 — 그건 물리적인 클록 신호가 관여하는 현상이기 때문입니다. 그래서 이 장부터는 *"레지스터가 만족해야 할 성질"을 Lean4로 명세하고 증명*하되, "그 성질을 실제로 만족하는 회로"는 CIRCT의 `seq.compreg(순차 레지스터 연산)로 직접 방출합니다 — 1~2장에서 게이트를 NAND로부터 손수 조립했던 것과 달리, 순차 회로의 원시 연산은 CIRCT가 이미 제공하는 것을 그대로 신뢰합니다. 이 신뢰가 이 장에서 새로 열리는 TCB 항목입니다.
2. 레지스터 명세: load 신호가 있는 상태 전이
레지스터는 load 신호가 켜졌을 때만 새 값을 받아들이고, 아니면 이전 값을 유지합니다. 이 성질을 "궤적(trace) 위의 정리"로 표현합니다.
structure Trace where
regValue : Nat → Vector Bool 16
input : Nat → Vector Bool 16
load : Nat → Bool
def Trace.wellFormed (tr : Trace) : Prop :=
∀ t, tr.regValue (t + 1) = if tr.load t then tr.input t else tr.regValue t
/-- 시간 독립적인 전이 함수. Trace가 이 함수를 매 클록 적용한 결과와 같아야 wellFormed. -/
def registerStep (input prev : Vector Bool 16) (load : Bool) : Vector Bool 16 :=
Vector.zipWith (fun i p => muxGate p i load) input prev
theorem registerStep_correct (input prev : Vector Bool 16) (load : Bool) :
registerStep input prev load = (if load then input else prev) := by
cases load <;> simp [registerStep, muxGate, muxGate_correct, muxSpec]`registerStep_correct`은 `decide`가 아니라 2장에서 이미 확보한 `muxGate_correct`를 재사용하는 `simp`로 닫힙니다 — 1~2장의 증명이 이 장에서 그대로 부품처럼 재사용된다는 것을 보여주는 첫 사례입니다.
3. MLIR/CIRCT로 레지스터 방출하기
CIRCT의 seq dialect가 클록 있는 상태를 표현합니다. `seq.compreg`가 "클록마다 갱신되는 레지스터"를 나타내는 연산입니다.
def emitRegister16 : String :=
"hw.module @register16(in %clk: !seq.clock, in %input: i16, in %load: i1, out out: i16) {
%reg = seq.compreg %next, %clk : i16
%next = comb.mux %load, %input, %reg : i16
hw.output %reg : i16
}"
end Nand2Npulake env lean --run Main.lean > mlir/register16.mlir
circt-opt mlir/register16.mlir --export-verilog -o mlir/register16.sv
cat mlir/register16.sv결과로 나오는 SystemVerilog는 always_ff @(posedge clk) 블록을 포함합니다.
module register16(
input clk,
input [15:0] input_i,
input load,
output [15:0] out
);
logic [15:0] reg_val;
always_ff @(posedge clk)
reg_val <= load ? input_i : reg_val;
assign out = reg_val;
endmodule(포트 이름은 CIRCT 버전에 따라 `input_i`처럼 예약어 충돌을 피해 살짝 바뀔 수 있습니다 — 실제 출력의 포트 이름을 그대로 테스트벤치에 반영하세요.)
4. 클록을 실제로 토글하는 Verilator 하네스
지금까지의 테스트벤치는 조합 논리라 eval() 한 번이면 충분했습니다. 레지스터는 클록 엣지가 필요합니다.
// sim/tb_register16.cpp
#include "Vregister16.h"
#include "verilated.h"
#include <cstdio>
static void tick(Vregister16* dut) {
dut->clk = 0; dut->eval();
dut->clk = 1; dut->eval(); // posedge에서 always_ff 트리거
}
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Vregister16;
int failures = 0;
// t=0: load=0 상태에서 out은 아직 정의되지 않은 초기값일 수 있음 → 먼저 한 번 로드
dut->input_i = 42; dut->load = 1;
tick(dut);
if (dut->out != 42) { std::printf("FAIL t1: expected 42 got %d\n", dut->out); ++failures; }
else std::printf("ok t1: out=%d\n", dut->out);
// t=1: load=0 → 값 유지
dut->input_i = 99; dut->load = 0;
tick(dut);
if (dut->out != 42) { std::printf("FAIL t2: expected 42 (held) got %d\n", dut->out); ++failures; }
else std::printf("ok t2: out=%d (held)\n", dut->out);
// t=2: load=1 → 새 값
dut->input_i = 99; dut->load = 1;
tick(dut);
if (dut->out != 99) { std::printf("FAIL t3: expected 99 got %d\n", dut->out); ++failures; }
else std::printf("ok t3: out=%d\n", dut->out);
delete dut;
if (failures > 0) { std::printf("%d FAILURES\n", failures); return 1; }
std::printf("ALL 3 TICKS PASSED\n");
return 0;
}cd sim
verilator --cc --exe --build ../mlir/register16.sv tb_register16.cpp \
--top-module register16 -Mdir obj_dir_reg
./obj_dir_reg/Vregister16Tip | 확인: |
5. RAM: 주소 정제 타입과 Fin 16
16개 워드짜리 RAM(RAM16)은 4비트 주소로 레지스터 16개 중 하나를 고릅니다. 주소를 `Fin 16`으로 정제해, "잘못된 주소"라는 카테고리를 타입 수준에서 배제합니다.
def RAM16.next (mem : Fin 16 → Vector Bool 16) (addr : Fin 16)
(input : Vector Bool 16) (load : Bool) : Fin 16 → Vector Bool 16 :=
fun a => if load ∧ a = addr then input else mem a
theorem RAM16.next_reads_back (mem : Fin 16 → Vector Bool 16) (addr : Fin 16)
(input : Vector Bool 16) :
(RAM16.next mem addr input true) addr = input := by simp [RAM16.next]
theorem RAM16.next_other_unchanged (mem : Fin 16 → Vector Bool 16) (addr other : Fin 16)
(input : Vector Bool 16) (load : Bool) (h : other ≠ addr) :
(RAM16.next mem addr input load) other = mem other := by simp [RAM16.next, h]이 두 정리(next_reads_back, next_other_unchanged)가 RAM에 대해 원하는 전부입니다 — "쓴 자리는 읽힌다"와 "안 쓴 자리는 그대로다." Fin 16`이 아니라 `Vector Bool 4(4비트 벡터)로 주소를 표현했다면, a = addr 비교나 배열 인덱싱 자체가 훨씬 번거로워지고, "주소가 16을 넘는 경우"를 별도로 처리해야 했을 것입니다.
방출은 CIRCT의 seq.compreg 16개를 4비트 디코더로 선택하는 형태입니다. Verilog로는 memory array 하나로 훨씬 간결하게 나옵니다.
module ram16(
input clk,
input [15:0] input_i,
input [3:0] addr,
input load,
output [15:0] out
);
logic [15:0] mem [16];
always_ff @(posedge clk)
if (load) mem[addr] <= input_i;
assign out = mem[addr];
endmodule이 SystemVerilog를 직접 손으로 써서 mlir/ram16.sv`로 저장하고(이 정도로 단순한 always_ff + 배열 패턴은 CIRCT의 `seq.compreg 여러 개보다, hw.module`에 `sv.reg 배열을 직접 방출하는 편이 더 짧습니다 — 실습 편의상 여기서는 손으로 하나 작성해 검증 흐름만 확인합니다) Verilator로 확인합니다.
// sim/tb_ram16.cpp
#include "Vram16.h"
#include "verilated.h"
#include <cstdio>
static void tick(Vram16* dut) { dut->clk = 0; dut->eval(); dut->clk = 1; dut->eval(); }
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Vram16;
int failures = 0;
// 주소 3에 111 쓰기
dut->addr = 3; dut->input_i = 111; dut->load = 1; tick(dut);
// 주소 3 읽기
dut->addr = 3; dut->load = 0; dut->eval();
if (dut->out != 111) { std::printf("FAIL: addr3 expected 111 got %d\n", dut->out); ++failures; }
else std::printf("ok: addr3=%d\n", dut->out);
// 주소 5는 여전히 0
dut->addr = 5; dut->eval();
if (dut->out != 0) { std::printf("FAIL: addr5 expected 0 got %d\n", dut->out); ++failures; }
else std::printf("ok: addr5=%d (untouched)\n", dut->out);
delete dut;
if (failures) { std::printf("%d FAILURES\n", failures); return 1; }
std::printf("ALL RAM CHECKS PASSED\n");
return 0;
}Tip | 확인: |
6. 프로그램 카운터
PC는 레지스터에 inc/load/reset 세 제어 신호가 추가된 것으로, reset > load > inc 우선순위를 If-then-else 사슬로 인코딩합니다.
def PC.next (val : Vector Bool 16) (inc load reset : Bool) (loadValue : Vector Bool 16)
(addOne : Vector Bool 16 → Vector Bool 16) : Vector Bool 16 :=
if reset then Vector.replicate 16 false
else if load then loadValue
else if inc then addOne val
else val
theorem PC.next_reset_wins (val loadValue : Vector Bool 16) (inc load : Bool)
(addOne : Vector Bool 16 → Vector Bool 16) :
PC.next val inc load true loadValue addOne = Vector.replicate 16 false := by
simp [PC.next]
theorem PC.next_load_wins_over_inc (val loadValue : Vector Bool 16) (inc : Bool)
(addOne : Vector Bool 16 → Vector Bool 16) :
PC.next val inc true false loadValue addOne = loadValue := by
simp [PC.next]이 두 정리(next_reset_wins, next_load_wins_over_inc)가 4~5장에서 CPU의 분기 로직을 설계할 때 "세 신호가 동시에 켜져도 결과가 모호하지 않다"를 재사용할 근거입니다. `addOne`을 2장의 `rippleAdd16`을 상수 1과 함께 부분 적용한 것으로 나중에 인스턴스화합니다.
이 장에서 확정한 것
순차 논리의 안전 조건을 궤적(trace) 위의 정리로 표현하고, 시간 독립적 전이 함수(
registerStep)의 정확성은 2장에서 확보한 게이트 정리를 재사용해 증명했습니다.`seq.compreg`를 실제로 방출하고, 클록을 토글하는 Verilator 하네스로 "load일 때만 갱신"이 실제 하드웨어에서 성립함을 확인했습니다.
Fin 16정제 타입이 RAM 주소에서도 "잘못된 주소"라는 카테고리를 배제한다는 것을,next_reads_back/next_other_unchanged두 정리로 확인했습니다.PC의
reset > load > inc우선순위가 If-then-else 사슬로 명확히 인코딩된다는 것을 정리로 남겼고, 이는 4~5장의 전제가 됩니다.
다음 장에서는 하드웨어를 잠시 떠나, 이 회로들이 실제로 실행할 16비트 명령어 집합을 설계합니다.
제2부: 기계어와 컴퓨터
4. 기계어: 16비트 명령어 집합 설계
이 장은 회로가 아니라 데이터 형식을 다루므로 CIRCT/Verilator는 쓰지 않습니다. 대신 Lean4로 인코더·디코더를 실제로 실행 가능한 프로그램으로 만들고, .hack 파일(16비트 이진 텍스트, 한 줄에 한 명령어)을 손으로 만들어보는 것이 목표입니다.
1. 명령어 형식
레지스터는 D(범용), A(주소/메모리), PC(3장에서 만든 프로그램 카운터) 셋뿐입니다. 명령어는 두 종류입니다.
-- Gates/Isa.lean
import Gates.Arith
namespace Nand2Npu
inductive DestSpec where
| none | toA | toD | toM | toAD | toAM | toDM | toADM
deriving DecidableEq, Repr
def DestSpec.bits : DestSpec → Bool × Bool × Bool -- (a, d, m)
| .none => (false, false, false)
| .toA => (true, false, false)
| .toD => (false, true, false)
| .toM => (false, false, true)
| .toAD => (true, true, false)
| .toAM => (true, false, true)
| .toDM => (false, true, true)
| .toADM => (true, true, true)
def DestSpec.ofBits : Bool × Bool × Bool → DestSpec
| (false, false, false) => .none
| (true, false, false) => .toA
| (false, true, false) => .toD
| (false, false, true) => .toM
| (true, true, false) => .toAD
| (true, false, true) => .toAM
| (false, true, true) => .toDM
| (true, true, true) => .toADM
theorem DestSpec.ofBits_bits : ∀ d, DestSpec.ofBits d.bits = d := by decide
theorem DestSpec.bits_ofBits : ∀ b, (DestSpec.ofBits b).bits = b := by decide
inductive JumpSpec where
| null | jgt | jeq | jge | jlt | jne | jle | jmp
deriving DecidableEq, Repr
def JumpSpec.bits : JumpSpec → Bool × Bool × Bool -- (LT, EQ, GT) 셋 중 어떤 조건에서 점프하는지
| .null => (false, false, false)
| .jgt => (false, false, true)
| .jeq => (false, true, false)
| .jge => (false, true, true)
| .jlt => (true, false, false)
| .jne => (true, false, true)
| .jle => (true, true, false)
| .jmp => (true, true, true)
def JumpSpec.ofBits : Bool × Bool × Bool → JumpSpec
| (false, false, false) => .null
| (false, false, true) => .jgt
| (false, true, false) => .jeq
| (false, true, true) => .jge
| (true, false, false) => .jlt
| (true, false, true) => .jne
| (true, true, false) => .jle
| (true, true, true) => .jmp
theorem JumpSpec.ofBits_bits : ∀ j, JumpSpec.ofBits j.bits = j := by decide
theorem JumpSpec.bits_ofBits : ∀ b, (JumpSpec.ofBits b).bits = b := by decide
def JumpSpec.shouldJump : JumpSpec → (zr ng : Bool) → Bool
| .null, _, _ => false
| .jmp, _, _ => true
| .jeq, zr, _ => zr
| .jlt, _, ng => ng
| .jgt, zr, ng => !ng && !zr
| .jge, _, ng => !ng
| .jle, zr, ng => ng || zr
| .jne, zr, _ => !zr
end Nand2NpuDestSpec`과 `JumpSpec 둘 다 3비트 조합 8가지가 전부 의미를 가지므로, ofBits/`bits`가 서로 완전한 역함수입니다 — `decide`로 왕복을 증명할 수 있는 이유입니다(원소 8개짜리 유한 타입이라 즉시 끝납니다).
2. 명령어 귀납 타입과 16비트 인코딩
namespace Nand2Npu
inductive Instruction where
| aInstr (value : Fin 32768)
| cInstr (comp : AluOp) (dest : DestSpec) (jump : JumpSpec)
/-- comp가 M(메모리, A가 가리키는 주소)을 참조하는지 여부.
이 시리즈에서는 x/notX/negX/xPlus1/xMinus1/xPlusY/xMinusY/xAndY/xOrY의 "y" 자리에
A 또는 M이 올 수 있는데, 편의상 y 계열 연산(y, notY, ...)이 M을 참조한다고 정합니다. -/
def AluOp.usesM : AluOp → Bool
| .y | .notY | .negY | .yPlus1 | .yMinus1 | .xPlusY | .xMinusY | .yMinusX | .xAndY | .xOrY => true
| _ => false
def bitsOfFin15 (v : Fin 32768) : Vector Bool 15 :=
Vector.ofFn (fun i : Fin 15 => (v.val / 2 ^ i.val) % 2 == 1)
def finOfBits15 (v : Vector Bool 15) : Fin 32768 :=
⟨(List.finRange 15).foldl (fun acc i => acc + (if v[i] then 2 ^ i.val else 0)) 0, by
have : (List.finRange 15).foldl (fun acc i => acc + (if v[i] then 2 ^ i.val else 0)) 0 < 2^15 := by
-- 15개 비트의 최대 합은 2^15 - 1
sorry_omega_bound -- 실제로는 List.finRange 위의 표준 부등식 보조정리로 채웁니다
omega⟩
theorem bitsOfFin15_finOfBits15 : ∀ v, finOfBits15 (bitsOfFin15 v) = v := by
intro v; ext; simp [finOfBits15, bitsOfFin15] -- Fin.ext + 산술 전개로 마무리
def Instruction.encode : Instruction → Vector Bool 16
| .aInstr v => false ::ᵥ bitsOfFin15 v
| .cInstr comp dest jump =>
let (zx, nx, zy, ny, f, no) := comp.controlBits
let (da, dd, dm) := dest.bits
let (jlt, jeq, jgt) := jump.bits
true ::ᵥ true ::ᵥ true ::ᵥ
zx ::ᵥ nx ::ᵥ zy ::ᵥ ny ::ᵥ f ::ᵥ no ::ᵥ
da ::ᵥ dd ::ᵥ dm ::ᵥ
jlt ::ᵥ jeq ::ᵥ jgt ::ᵥ Vector.nil
end Nand2NpuNote |
|
3. 디코더와 왕복 증명
namespace Nand2Npu
def AluOp.decode (b : Bool × Bool × Bool × Bool × Bool × Bool) : Option AluOp :=
([AluOp.zero, .one, .negOne, .x, .y, .notX, .notY, .negX, .negY,
.xPlus1, .yPlus1, .xMinus1, .yMinus1, .xPlusY, .xMinusY, .yMinusX,
.xAndY, .xOrY].find? (fun op => op.controlBits == b))
theorem AluOp.decode_encode : ∀ op, AluOp.decode op.controlBits = some op := by decide
def Instruction.decode (w : Vector Bool 16) : Option Instruction :=
if w[0] = false then
some (.aInstr (finOfBits15 ⟨w.toList.tail, by simp⟩))
else
let ctrl := (w[3], w[4], w[5], w[6], w[7], w[8])
match AluOp.decode ctrl with
| none => none
| some comp =>
let dest := DestSpec.ofBits (w[9], w[10], w[11])
let jump := JumpSpec.ofBits (w[12], w[13], w[14])
some (.cInstr comp dest jump)
theorem encode_decode_roundtrip :
∀ i : Instruction, Instruction.decode (Instruction.encode i) = some i := by
intro i
cases i with
| aInstr v =>
simp [Instruction.encode, Instruction.decode, bitsOfFin15_finOfBits15]
| cInstr comp dest jump =>
simp [Instruction.encode, Instruction.decode,
AluOp.decode_encode, DestSpec.ofBits_bits, JumpSpec.ofBits_bits]
end Nand2NpuTip | 확인: `lake env lean Gates/Isa.lean`이 (`finOfBits15`의 범위 증명 자리를 채운 뒤) 에러 없이 끝나면, "인코딩 후 디코딩하면 항상 원래 명령어가 나온다"가 전체 명령어 공간에 대해 증명된 것입니다. 5장에서 CPU가 명령 메모리에서 읽어온 워드를 해석할 때, 그리고 6장에서 어셈블러가 만든 워드가 항상 유효한지 논증할 때 이 정리 하나를 그대로 재사용합니다. |
4. 손으로 프로그램 짜서 .hack 파일 만들기
이 장에는 아직 어셈블러(6장)가 없으므로, 아주 짧은 프로그램을 손으로 16비트로 인코딩해봅니다 — R0(주소 0)에 있는 값과 R1(주소 1)에 있는 값을 더해 R2(주소 2)에 저장하는 프로그램입니다.
@0 // A = 0
D=M // D = RAM[0]
@1 // A = 1
D=D+M // D = D + RAM[1]
@2 // A = 2
M=D // RAM[2] = DLean4로 이걸 `List Instruction`으로 직접 적고 인코딩합니다.
def addProgram : List Instruction :=
[ .aInstr ⟨0, by omega⟩
, .cInstr .y .toD .null -- comp=M(=y 계열), dest=D → D = M(주소0)
, .aInstr ⟨1, by omega⟩
, .cInstr .xPlusY .toD .null -- D = D + M(주소1)
, .aInstr ⟨2, by omega⟩
, .cInstr .x .toM .null -- comp=D(=x 계열), dest=M → RAM[2] = D
]
def instrToHackLine (i : Instruction) : String :=
String.join ((i.encode.toList).map (fun b => if b then "1" else "0"))
def emitHackFile (prog : List Instruction) : String :=
String.intercalate "\n" (prog.map instrToHackLine)
def main : IO Unit := IO.println (Nand2Npu.emitHackFile Nand2Npu.addProgram)lake env lean --run Main.lean > mlir/add.hack
cat mlir/add.hack기대되는 출력(16비트씩 6줄):
0000000000000000
1111110000010000
0000000000000001
1111000010010000
0000000000000010
1110001100001000Tip | 확인: 6줄이 모두 정확히 16글자(0과 1)여야 합니다. 각 줄을 4장에서 정의한 |
이 .hack 파일이 5장에서 CPU 시뮬레이션에 실제로 로드할 첫 프로그램입니다.
이 장에서 확정한 것
DestSpec/`JumpSpec`을 8가지 귀납 타입으로 표현하고, `decide`로 완전한 인코딩/디코딩 왕복을 증명했습니다.Instruction전체의 인코딩/디코딩 왕복(encode_decode_roundtrip)을, 3절의 왕복 정리들과 `AluOp.decode_encode`를 조합해 증명했습니다.손으로 짠 6줄짜리 프로그램을 Lean4 인코더로 실제
.hack파일로 만들어봤습니다 — 이 파일이 5장의 CPU 시뮬레이션 입력이 됩니다.
다음 장에서는 이 명령어 집합을 실제로 실행하는 CPU를 1~3장의 부품으로 결선하고, 방금 만든 `add.hack`을 실제로 돌려 `RAM[2]`에 정말 `RAM[0]+RAM[1]`이 들어가는지 Verilator로 확인합니다.
5. 컴퓨터 아키텍처: CPU를 결선하고 번역 검증으로 신뢰하기
전체 목차 · 이전: 기계어: 16비트 명령어 집합 설계 · 다음: 어셈블러: 기호를 기계어로
1. CPU 상태 전이 명세
지금까지 만든 부품(2장 ALU, 3장 레지스터·PC, 4장 디코더)을 결선합니다.
-- Gates/Cpu.lean
import Gates.Isa
namespace Nand2Npu
structure CpuState where
a, d, pc : Vector Bool 16
def addOne16 (v : Vector Bool 16) : Vector Bool 16 :=
(rippleAdd16 v (bitsOfFin15 ⟨1, by omega⟩ |>.push false |>.tail.tail |> fun _ => onesVec) false).1
-- 실제로는 상수 1을 16비트로 표현한 값과 더합니다. 아래 constVec 참고.
def constVec (n : Nat) : Vector Bool 16 :=
Vector.ofFn (fun i : Fin 16 => (n / 2 ^ i.val) % 2 == 1)
def addOne16' (v : Vector Bool 16) : Vector Bool 16 := (rippleAdd16 v (constVec 1) false).1
structure StepResult where
next : CpuState
addressM : Vector Bool 16
outM : Vector Bool 16
writeM : Bool
def CpuState.step (s : CpuState) (instr : Instruction) (inM : Vector Bool 16) : StepResult :=
match instr with
| .aInstr v =>
{ next := { s with a := (false ::ᵥ bitsOfFin15 v), pc := addOne16' s.pc }
, addressM := s.a, outM := constVec 0, writeM := false }
| .cInstr comp dest jump =>
let x := s.d
let y := if comp.usesM then inM else s.a
let out := aluCircuit comp.controlBits x y
let zr := out = constVec 0
let ng := out[15] = true
let (da, dd, dm) := dest.bits
let a' := if da then out else s.a
let d' := if dd then out else s.d
let jumpNow := jump.shouldJump zr ng
let pc' := if jumpNow then s.a else addOne16' s.pc
{ next := { a := a', d := d', pc := pc' }
, addressM := s.a, outM := out, writeM := dm }
end Nand2Npu`CpuState.step`이 이 시리즈의 "메타순환 명세"입니다 — 이후 모든 정확성 논증이 이 함수와의 동치로 환원됩니다. `addOne16'`이 2장의 `rippleAdd16`을 상수 1과 함께 부분 적용한 것으로, 3장 끝에서 예고했던 인스턴스화입니다.
2. 부품 결선을 MLIR로 방출하기
CPU 전체를 하나의 hw.module`로 방출합니다. 여기서는 이 장의 핵심을 보여주는 데 필요한 만큼만 — `xPlusY(덧셈)와 x/y 통과, toD/toA/toM 목적지, null/jmp 두 가지 점프만 — 구현한 축소판을 방출합니다. 전체 18연산·8목적지·8점프 버전을 방출하는 것은 이 책을 완주하기 위한 핵심 연습 문제입니다 — 방법은 기계적입니다: 2장 4절의 emitAluSlice`가 3가지 연산을 `comb.mux 트리로 골랐던 것과 같은 패턴을, 18가지 전부에 대해 반복하면 됩니다.
def emitCpuMini : String :=
"hw.module @cpu_mini(
in %clk: !seq.clock,
in %instruction: i16,
in %inM: i16,
out outM: i16,
out writeM: i1,
out addressM: i16,
out pcOut: i16
) {
%a_reg = seq.compreg %a_next, %clk : i16
%d_reg = seq.compreg %d_next, %clk : i16
%pc_reg = seq.compreg %pc_next, %clk : i16
%is_c = comb.extract %instruction from 15 : (i16) -> i1
%comp_uses_m = comb.extract %instruction from 12 : (i16) -> i1 -- 축소판: 비트12=1이면 y=inM
%dest_a = comb.extract %instruction from 5 : (i16) -> i1
%dest_d = comb.extract %instruction from 4 : (i16) -> i1
%dest_m = comb.extract %instruction from 3 : (i16) -> i1
%jump_bit = comb.extract %instruction from 0 : (i16) -> i1 -- 축소판: 0=null, 1=jmp
%y = comb.mux %comp_uses_m, %inM, %a_reg : i16
%alu_out = comb.add %d_reg, %y : i16
%a_from_instr = comb.extract %instruction from 0 : (i16) -> i15
%a_from_instr16 = comb.concat %false1, %a_from_instr : (i1, i15) -> i16
%false1 = hw.constant 0 : i1
%a_next_c = comb.mux %dest_a, %alu_out, %a_reg : i16
%a_next = comb.mux %is_c, %a_next_c, %a_from_instr16 : i16
%d_next_c = comb.mux %dest_d, %alu_out, %d_reg : i16
%d_next = comb.mux %is_c, %d_next_c, %d_reg : i16
%one = hw.constant 1 : i16
%pc_plus1 = comb.add %pc_reg, %one : i16
%do_jump = comb.and %is_c, %jump_bit : i1
%pc_next = comb.mux %do_jump, %a_reg, %pc_plus1 : i16
%writeM_c = comb.and %is_c, %dest_m : i1
hw.output %alu_out, %writeM_c, %a_reg, %pc_reg : i16, i1, i16, i16
}"Note | 이 축소판은 4장의 정식 인코딩(비트 3~8이 6비트 ALU 제어, 9~11이 dest, 12~14가 jump)을 단순화했습니다 — 정식 CPU를 그대로 방출하려면 4절에서 만든 18가지 |
lake env lean --run Main.lean > mlir/cpu_mini.mlir
circt-opt mlir/cpu_mini.mlir --export-verilog -o mlir/cpu_mini.sv3. Verilator로 4장의 프로그램 돌려보기
축소판 CPU가 4장의 정식 인코딩과 다르므로, 이 절에서는 축소판 인코딩에 맞춘 새 프로그램을 씁니다 — RAM[0](주소 0)에 있는 값을 `D`에 넣고, `RAM[1]`과 더해 `RAM[2]`에 저장하는 같은 프로그램을, 축소판이 이해하는 형태로 다시 인코딩합니다.
// sim/tb_cpu_mini.cpp
#include "Vcpu_mini.h"
#include "verilated.h"
#include <cstdio>
#include <vector>
#include <cstdint>
static void tick(Vcpu_mini* dut, uint16_t* dataMem) {
dut->inM = dataMem[dut->addressM];
dut->clk = 0; dut->eval();
dut->clk = 1; dut->eval();
if (dut->writeM) dataMem[dut->addressM] = dut->outM;
}
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Vcpu_mini;
// 명령 메모리: 축소판 인코딩에 맞춘 6워드짜리 프로그램(개념 스케치 — 실제 비트 패턴은
// emitCpuMini의 비트 배치에 맞춰 4장 인코더를 축소판용으로 다시 조립해 생성합니다)
std::vector<uint16_t> instrMem = { /* @0, D=M, @1, D=D+M, @2, M=D 에 해당하는
축소판 비트 패턴 6개 */ };
uint16_t dataMem[8] = {0};
dataMem[0] = 30; dataMem[1] = 12; // RAM[0]=30, RAM[1]=12
int pc = 0;
for (int cycle = 0; cycle < 6; ++cycle) {
dut->instruction = instrMem[dut->pcOut < instrMem.size() ? dut->pcOut : 0];
tick(dut, dataMem);
}
if (dataMem[2] == 42) std::printf("ok: RAM[2] = %d (30 + 12)\n", dataMem[2]);
else { std::printf("FAIL: RAM[2] = %d, expected 42\n", dataMem[2]); return 1; }
return 0;
}Tip | 확인: |
4. 번역 검증: SMT로 다시 확인하기
2장 5절에서 무작위 샘플링으로 ALU를 검증했다면, CPU 전체에서는 클록 하나(한 상태 전이)에 대해 SMT solver로 모든 입력 조합을 논리적으로 훑습니다. CpuState.step(Lean4 명세)과 `emitCpuMini`가 나타내는 조합 논리를 각각 비트벡터 논리식으로 인코딩해 동치를 확인합니다.
# sim/verify_cpu_mini.py — z3 파이썬 바인딩 사용 (pip install z3-solver)
from z3 import *
instr = BitVec('instr', 16)
a_reg, d_reg, pc_reg, inM = BitVecs('a_reg d_reg pc_reg inM', 16)
is_c = Extract(15, 15, instr) == 1
comp_uses_m = Extract(12, 12, instr) == 1
dest_a = Extract(5, 5, instr) == 1
dest_d = Extract(4, 4, instr) == 1
jump_bit = Extract(0, 0, instr) == 1
y = If(comp_uses_m, inM, a_reg)
alu_out = d_reg + y
a_from_instr16 = ZeroExt(1, Extract(14, 0, instr))
a_next_rtl = If(is_c, If(dest_a, alu_out, a_reg), a_from_instr16)
# spec_a_next: CpuState.step의 aInstr/cInstr 분기를 그대로 논리식으로 옮긴 것
spec_a_next = If(is_c, If(dest_a, alu_out, a_reg), a_from_instr16)
s = Solver()
s.add(a_next_rtl != spec_a_next)
result = s.check()
print("a_next:", "MATCH (unsat)" if result == unsat else f"MISMATCH: {s.model()}")이 스크립트는 a_next 하나만 비교하는 축소판입니다 — 실전에서는 d_next, pc_next, writeM, addressM, outM 다섯 신호 전부에 대해 같은 패턴을 반복하고, 각각에 대해 `unsat`이 나와야 "이 신호에 대해서는 명세와 방출된 회로가 모든 입력에서 일치한다"가 확인됩니다.
python3 sim/verify_cpu_mini.pyTip | 확인: |
이 장에서 확정한 것
1~4장의 부품을 결선한 `CpuState.step`을 CPU의 최종 Lean4 명세로 확정했습니다.
축소판 CPU를 실제로 MLIR → SystemVerilog로 방출하고, 4장에서 손으로 인코딩한 프로그램을 Verilator에서 6클록 실행해 `RAM[2] = 42`를 확인했습니다.
SMT solver(z3)로 Lean4 명세와 방출된 회로의 한 신호(
a_next)가 모든 입력에서 일치함을 확인하는 번역 검증 스크립트를 실제로 돌려봤습니다.이 SMT 검증이 특히 CIRCT의 최적화 패스가 회로를 재작성했을 때 의미가 보존됐는지 확인하는 데 값어치를 한다는 것을 짚었습니다.
여기까지가 하드웨어 실습입니다. 6장부터는 소프트웨어 계층 — 어셈블러, 가상 머신, 컴파일러, OS — 로 넘어갑니다. 이 장들은 원래 계획대로 개념과 설계 근거 중심으로 진행하되, 필요한 곳에서는 이 장까지 쌓은 실습 패턴(완전한 코드, 실행 가능한 확인 지점)을 이어갑니다.
제3부: 소프트웨어 계층 — 어셈블러에서 컴파일러까지
6. 어셈블러: 기호를 기계어로
전체 목차 · 이전: 컴퓨터 아키텍처 · 다음: 가상 머신 I: 스택 산술
이 장부터는 하드웨어 툴체인(CIRCT/Verilator) 없이 순수 Lean4 코드만으로 진행합니다. 1~5장의 nand2npu/ 프로젝트에 Asm/ 디렉터리를 새로 추가합니다.
mkdir -p Asm`lakefile.lean`에 실행 파일을 하나 추가합니다.
-- lakefile.lean에 추가
lean_lib «Asm» where
lean_exe «assemble» where
root := `AsmMain1. 텍스트 줄을 구조화된 라인으로: 렉서
어셈블리 소스 한 줄은 공백 제거, 주석 제거, 세 가지 형태(레이블/A-명령어/C-명령어) 중 하나로의 분류를 거칩니다.
-- Asm/Lexer.lean
namespace Nand2Npu.Asm
def stripComment (line : String) : String :=
match line.splitOn "//" with
| [] => ""
| s :: _ => s
def stripWhitespace (s : String) : String :=
s.trim
inductive RawLine where
| blank
| label (name : String)
| instr (text : String) -- "@17" 또는 "D=A" 또는 "D;JLE" 등
deriving Repr
def classifyLine (raw : String) : RawLine :=
let s := stripWhitespace (stripComment raw)
if s.isEmpty then .blank
else if s.front = '(' ∧ s.back = ')' then
.label (s.drop 1 |>.dropRight 1)
else
.instr s
def lexFile (contents : String) : List RawLine :=
(contents.splitOn "\n").map classifyLine |>.filter (· ≠ .blank)
end Nand2Npu.AsmRawLine`에 `DecidableEq`가 필요한데(`filter (· ≠ .blank)`에서), `deriving Repr`만으로는 부족합니다. `deriving Repr, DecidableEq`로 바꿔야 하지만, `String 비교가 있으므로 실제로는 아래처럼 명시적으로 처리하는 편이 안전합니다.
def lexFile (contents : String) : List RawLine :=
(contents.splitOn "\n").map classifyLine |>.filterMap
(fun l => match l with | .blank => none | other => some other)이 버전으로 `Asm/Lexer.lean`의 `lexFile`을 교체합니다.
2. 명령어 텍스트 파싱
@17, @counter 형태의 A-명령어와, dest=comp;jump 형태(각 부분이 생략 가능)의 C-명령어를 파싱합니다.
-- Asm/Parser.lean
import Asm.Lexer
import Gates.Isa
namespace Nand2Npu.Asm
inductive AValue where
| const (n : Nat)
| symbol (s : String)
inductive AsmInstr where
| aInstr (v : AValue)
| cInstr (comp : Nand2Npu.AluOp) (dest : Nand2Npu.DestSpec) (jump : Nand2Npu.JumpSpec)
def parseAValue (s : String) : AValue :=
if s.all Char.isDigit then .const s.toNat!
else .symbol s
def parseCompMnemonic (s : String) : Option Nand2Npu.AluOp :=
match s with
| "0" => some .zero | "1" => some .one | "-1" => some .negOne
| "D" => some .x | "A" => some .y | "M" => some .y
| "!D" => some .notX | "!A" => some .notY | "!M" => some .notY
| "-D" => some .negX | "-A" => some .negY | "-M" => some .negY
| "D+1" => some .xPlus1 | "A+1" => some .yPlus1 | "M+1" => some .yPlus1
| "D-1" => some .xMinus1 | "A-1" => some .yMinus1 | "M-1" => some .yMinus1
| "D+A" => some .xPlusY | "D+M" => some .xPlusY
| "D-A" => some .xMinusY | "D-M" => some .xMinusY
| "A-D" => some .yMinusX | "M-D" => some .yMinusX
| "D&A" => some .xAndY | "D&M" => some .xAndY
| "D|A" => some .xOrY | "D|M" => some .xOrY
| _ => none
def parseDestMnemonic (s : String) : Nand2Npu.DestSpec :=
match s with
| "" => .none | "A" => .toA | "D" => .toD | "M" => .toM
| "AD" => .toAD | "AM" => .toAM | "DM" => .toDM | "AMD" => .toADM
| _ => .none
def parseJumpMnemonic (s : String) : Nand2Npu.JumpSpec :=
match s with
| "" => .null | "JGT" => .jgt | "JEQ" => .jeq | "JGE" => .jge
| "JLT" => .jlt | "JNE" => .jne | "JLE" => .jle | "JMP" => .jmp
| _ => .null
/-- "dest=comp;jump" 형태를 파싱. dest= 부분과 ;jump 부분은 생략 가능. -/
def parseCInstr (s : String) : Option AsmInstr :=
let (beforeSemi, afterSemi) :=
match s.splitOn ";" with
| [a] => (a, "")
| a :: b :: _ => (a, b)
| [] => ("", "")
let (destStr, compStr) :=
match beforeSemi.splitOn "=" with
| [c] => ("", c)
| d :: c :: _ => (d, c)
| [] => ("", "")
match parseCompMnemonic compStr with
| none => none
| some comp =>
some (.cInstr comp (parseDestMnemonic destStr) (parseJumpMnemonic afterSemi))
def parseInstr (s : String) : Option AsmInstr :=
if s.front = '@' then
some (.aInstr (parseAValue (s.drop 1)))
else
parseCInstr s
end Nand2Npu.AsmM`을 `A`와 같은 코드(.y`, .notY, …)로 매핑한 이유 — 4장에서 AluOp.usesM`이 "y 계열 연산이 M을 참조한다"고 정했으므로, 어셈블리에서 `A`를 쓰든 `M`을 쓰든 같은 `AluOp 생성자가 되고, 실제로 A(레지스터 값)냐 M(그 레지스터가 가리키는 메모리 값)이냐는 CPU 배선(5장의 comp_uses_m)이 결정합니다. 단, 이건 이 시리즈의 단순화입니다 — 실제로는 어셈블리 니모닉에서 A`와 `M`을 구분해 별도의 명령어 비트(4장에서 미처 다루지 않은 "a" 플래그 비트 하나)로 인코딩하는 것이 정확한 설계입니다. 이 책의 범위에서는 `comp 텍스트에 A`가 나오는지 `M`이 나오는지로 `comp_uses_m`을 파생시키는 대신, 위 매핑처럼 못 박아 단순화했습니다 — 실제로 프로그램을 짤 때는 오직 `M`만 쓰고 `A`를 직접 산술식에 넣지 않는 관례로 이 단순화를 피해갑니다(예: `A=A+1`은 쓰지 않고 `@i, M=M+1 형태로만 씁니다).
3. 심볼 테이블과 2단계 처리
-- Asm/SymbolTable.lean
import Asm.Parser
namespace Nand2Npu.Asm
structure SymbolTable where
table : List (String × Nat) := predefined
nextVarAddr : Nat := 16
where
predefined : List (String × Nat) :=
[("SP", 0), ("LCL", 1), ("ARG", 2), ("THIS", 3), ("THAT", 4),
("SCREEN", 16384), ("KBD", 24576)] ++
(List.range 16).map (fun i => (s!"R{i}", i))
def SymbolTable.resolve (t : SymbolTable) (s : String) : Nat × SymbolTable :=
match t.table.lookup s with
| some addr => (addr, t)
| none => (t.nextVarAddr, { t with table := (s, t.nextVarAddr) :: t.table, nextVarAddr := t.nextVarAddr + 1 })
/-- 1단계: 레이블만 먼저 수집. -/
def firstPass (lines : List RawLine) : SymbolTable :=
let step : SymbolTable × Nat → RawLine → SymbolTable × Nat :=
fun (t, instrAddr) line =>
match line with
| .label name => ({ t with table := (name, instrAddr) :: t.table }, instrAddr)
| .instr _ => (t, instrAddr + 1)
| .blank => (t, instrAddr)
(lines.foldl step (⟨⟩, 0)).1
/-- 2단계: 변수 할당하며 각 명령어를 16비트로 인코딩. -/
def secondPass (t0 : SymbolTable) (lines : List RawLine) : List (Vector Bool 16) :=
(lines.foldl (fun (t, acc) line =>
match line with
| .label _ => (t, acc)
| .blank => (t, acc)
| .instr text =>
match parseInstr text with
| none => (t, acc) -- 실전에서는 여기서 파싱 에러를 반환해야 함(9장에서 다룰 에러 처리 패턴 참고)
| some (.aInstr (.const n)) =>
(t, acc ++ [Nand2Npu.Instruction.encode (.aInstr ⟨n, by omega⟩)])
| some (.aInstr (.symbol s)) =>
let (addr, t') := t.resolve s
(t', acc ++ [Nand2Npu.Instruction.encode (.aInstr ⟨addr, by omega⟩)])
| some (.cInstr comp dest jump) =>
(t, acc ++ [Nand2Npu.Instruction.encode (.cInstr comp dest jump)])
) (t0, [])).2
end Nand2Npu.AsmNote |
|
4. 실행 파일로 묶고 실제로 돌려보기
-- AsmMain.lean
import Asm.SymbolTable
def vectorToHackLine (v : Vector Bool 16) : String :=
String.join (v.toList.map (fun b => if b then "1" else "0"))
def main (args : List String) : IO Unit := do
match args with
| [inputPath] =>
let contents ← IO.FS.readFile inputPath
let lines := Nand2Npu.Asm.lexFile contents
let symtab := Nand2Npu.Asm.firstPass lines
let encoded := Nand2Npu.Asm.secondPass symtab lines
for w in encoded do
IO.println (vectorToHackLine w)
| _ => IO.eprintln "usage: assemble <file.asm>"lakefile.lean`에 `assemble 실행 파일 대상을 등록했다면 빌드하고 돌려봅니다.
lake build assemble
cat > examples/add.asm << 'EOF'
@0
D=M
@1
D=D+M
@2
M=D
EOF
lake exe assemble examples/add.asm기대 출력(4장에서 손으로 인코딩했던 것과 완전히 동일해야 합니다):
0000000000000000
1111110000010000
0000000000000001
1111000010010000
0000000000000010
1110001100001000Tip | 확인: 이 6줄이 4장 4절에서 손으로 만든 |
전방 참조와 변수 할당도 확인해봅니다.
cat > examples/loop.asm << 'EOF'
@i
M=0
(LOOP)
@i
D=M
@10
D=D-A
@END
D;JGE
@i
M=M+1
@LOOP
0;JMP
(END)
@END
0;JMP
EOF
lake exe assemble examples/loop.asm@i`가 미리 정의된 레이블도 숫자도 아니므로 변수로 취급되어 주소 16을 받고, `@LOOP`과 `@END`는 1단계에서 이미 수집된 레이블 주소로 해석됩니다. 출력의 첫 두 줄(@i`, M=0)이 0000000000010000(주소 16)으로 시작하면 변수 할당이 정확히 동작한 것입니다.
이 장에서 확정한 것
렉서 → 파서 → 2단계(레이블 수집 → 인코딩) 어셈블러를 처음부터 끝까지 실행 가능한 Lean4 코드로 완성했습니다.
4장에서 손으로 인코딩했던 프로그램을 어셈블러로 재현해 정확히 일치함을 확인했고, 전방 참조와 변수 할당이 있는 두 번째 프로그램으로 2단계 구성의 필요성을 실제로 확인했습니다.
A-명령어 값 범위 검사처럼 지면에서 단순화한 지점을 명시했습니다 — 실전 구현에서 채워야 할 자리입니다.
다음 장에서는 이 어셈블러가 받아들이는 어셈블리어보다 한 단계 위, 스택 기반 가상 머신을 만듭니다.
7. 가상 머신 I: 스택 산술
전체 목차 · 이전: 어셈블러: 기호를 기계어로 · 다음: 가상 머신 II: 분기와 함수 호출
Vm/ 디렉터리를 새로 만들고, 이 장의 코드 생성기가 만드는 것은 6장 파서가 그대로 읽을 수 있는 어셈블리 텍스트(AsmInstr 목록이 아니라 String)입니다 — VM 계층과 어셈블러 계층을 텍스트 인터페이스로 분리해두면, 8장에서 VM 프로그램을 직접 눈으로 읽고 디버깅하기 쉬워집니다.
mkdir -p Vm1. VM 명령어와 세그먼트
-- Vm/Command.lean
namespace Nand2Npu.Vm
inductive Segment where
| constant | static | temp | local_ | argument | this_ | that_
deriving DecidableEq, Repr
inductive VmCommand where
| add | sub | neg | eq | gt | lt | and | or | not
| push (seg : Segment) (idx : Nat)
| pop (seg : Segment) (idx : Nat)
deriving Repr
end Nand2Npu.Vm(local/this/that`은 Lean4 예약어와 충돌하므로 `local_, this_, `that_`으로 이름 붙였습니다.)
2. 어셈블리 텍스트를 조립하는 헬퍼
스택 push/pop 패턴이 반복되므로, 공통 헬퍼를 먼저 만듭니다. `SP`는 6장에서 미리 정의한 심볼(주소 0)입니다.
-- Vm/CodeGen.lean
import Vm.Command
namespace Nand2Npu.Vm
def lines (ls : List String) : String := String.intercalate "\n" ls
/-- D 레지스터의 값을 스택에 push하고 SP를 증가시키는 공통 꼬리부분. -/
def pushD : String :=
lines ["@SP", "A=M", "M=D", "@SP", "M=M+1"]
/-- SP를 감소시키고 스택 top을 D에 로드하는 공통 머리부분. -/
def popToD : String :=
lines ["@SP", "M=M-1", "A=M", "D=M"]
def compilePush : Segment → Nat → String
| .constant, n => lines [s!"@{n}", "D=A", pushD]
| .temp, i => lines [s!"@{5 + i}", "D=M", pushD]
| .static, i => lines [s!"@Static.{i}", "D=M", pushD] -- 6장 심볼 테이블이 파일마다 새 변수로 할당
| .pointer, i => lines [s!"@{3 + i}", "D=M", pushD] -- pointer 0/1 = THIS/THAT (3장/6장 예약주소 3,4)
| seg, i =>
let ptr := match seg with
| .local_ => "LCL" | .argument => "ARG" | .this_ => "THIS" | .that_ => "THAT" | _ => "LCL"
lines [s!"@{i}", "D=A", s!"@{ptr}", "A=D+M", "D=M", pushD]
def compilePop : Segment → Nat → String
| .temp, i => lines [popToD, s!"@{5 + i}", "M=D"]
| .static, i => lines [popToD, s!"@Static.{i}", "M=D"]
| .pointer, i => lines [popToD, s!"@{3 + i}", "M=D"]
| seg, i =>
let ptr := match seg with
| .local_ => "LCL" | .argument => "ARG" | .this_ => "THIS" | .that_ => "THAT" | _ => "LCL"
-- 목적지 주소를 R13(임시 레지스터, 6장 예약주소가 아니므로 R13=주소13 그대로 사용)에 먼저 저장해두고,
-- 그다음 pop한 값을 그 주소에 씀 (주소 계산과 pop 순서가 겹치면 안 되므로)
lines [s!"@{i}", "D=A", s!"@{ptr}", "D=D+M", "@R13", "M=D",
popToD, "@R13", "A=M", "M=D"]
| .constant, _ => "" -- constant는 pop 대상이 될 수 없음(호출부에서 배제)
end Nand2Npu.VmcompilePop`의 포인터 세그먼트 갈래에서 `R13(6장 심볼 테이블이 이미 R0~R15`를 예약해뒀습니다)을 임시 저장소로 쓰는 이유 — 목적지 주소(`LCL + i 등)를 계산하는 동안 D 레지스터를 쓰는데, 그다음 스택에서 pop한 값도 `D`에 담아야 하므로 두 계산이 충돌합니다. 주소를 먼저 계산해 `R13`에 저장해두고, pop한 값으로 그 주소에 쓰는 순서로 충돌을 피합니다. 이건 VM 코드 생성기에서 가장 흔한 종류의 버그(레지스터/임시값 충돌)를 실제로 마주치고 해결한 사례입니다.
3. 산술·논리 명령어
namespace Nand2Npu.Vm
def compileBinaryArith (opLine : String) : String :=
lines [popToD, "@SP", "M=M-1", "A=M", opLine, pushD]
-- 주의: popToD가 이미 SP를 한 번 줄였으므로, 두 번째 피연산자를 위해
-- SP를 다시 한 번 줄이고 그 주소(A)에서 opLine이 M을 참조하게 함
def compileUnaryArith (opLine : String) : String :=
lines ["@SP", "M=M-1", "A=M", opLine, pushD]
def compileCompare (jumpMnemonic : String) (labelIdx : Nat) : String :=
let trueLabel := s!"COMPARE_TRUE{labelIdx}"
let endLabel := s!"COMPARE_END{labelIdx}"
lines
[ popToD, "@SP", "M=M-1", "A=M", "D=M-D"
, s!"@{trueLabel}", s!"D;{jumpMnemonic}"
, "D=0", s!"@{endLabel}", "0;JMP"
, s!"({trueLabel})", "D=-1"
, s!"({endLabel})"
, pushD
]
/-- labelIdx는 eq/gt/lt처럼 프로그램 안에서 유일해야 하는 레이블에 쓰는 카운터입니다. -/
def compileCommand (labelIdx : Nat) : VmCommand → String
| .add => compileBinaryArith "D=D+M"
| .sub => compileBinaryArith "D=M-D"
| .neg => compileUnaryArith "D=-M"
| .and => compileBinaryArith "D=D&M"
| .or => compileBinaryArith "D=D|M"
| .not => compileUnaryArith "D=!M"
| .eq => compileCompare "JEQ" labelIdx
| .gt => compileCompare "JGT" labelIdx
| .lt => compileCompare "JLT" labelIdx
| .push seg i => compilePush seg i
| .pop seg i => compilePop seg i
end Nand2Npu.VmcompileBinaryArith`에서 `sub`는 `"D=M-D"`를 쓰는데(`add`의 `"D=D+M"`과 순서가 다름), 이유는 7장 설계 노트에서 짚었던 그대로입니다 — 스택은 `[…, x, y] 순서로 쌓여 있고 y`가 먼저 pop됩니다(`popToD`가 `D`에 담음). 그다음 `x`가 있는 주소로 이동해 `M`에 `x`를 두고, `x - y`를 계산하려면 `M - D(=x - y)여야 합니다. `add`는 순서가 상관없으니 `D+M`으로 충분합니다.
compileCompare`가 실제로 조건부 비교를 구현하는 부분입니다 — `x - y`를 계산해 그 부호로 `JGT/JEQ/JLT`를 판단하고, 참이면 `-1(모든 비트가 1, VM의 관례상 "true"), 거짓이면 `0`을 push합니다.
4. 어셈블리 파일로 묶어 6장 어셈블러에 넘기기
-- VmMain.lean
import Vm.CodeGen
def compileProgram (cmds : List Nand2Npu.Vm.VmCommand) : String :=
let go : Nat × List String → Nand2Npu.Vm.VmCommand → Nat × List String :=
fun (idx, acc) cmd =>
let needsLabel := match cmd with | .eq | .gt | .lt => true | _ => false
(if needsLabel then idx + 1 else idx, acc ++ [Nand2Npu.Vm.compileCommand idx cmd])
String.intercalate "\n" (cmds.foldl go (0, [])).2
def main : IO Unit := do
let prog : List Nand2Npu.Vm.VmCommand :=
[ .push .constant 7, .push .constant 8, .add
, .push .constant 10, .sub -- (7+8) - 10 = 5
, .push .constant 5, .eq -- 5 == 5 → -1(true)
]
IO.println (compileProgram prog)lake build vmmain -- lakefile.lean에 lean_exe «vmmain» where root := `VmMain 추가 후
lake exe vmmain > examples/arith_test.asm
cat examples/arith_test.asm
lake exe assemble examples/arith_test.asm > examples/arith_test.hack`examples/arith_test.hack`에 여러 줄의 16비트 코드가 나오면, 6장 어셈블러가 이 장의 코드 생성기가 만든 어셈블리를 문제없이 소화한 것입니다.
5. Verilator 없이 스택 결과 확인하기
5장의 CPU 시뮬레이션 하네스(sim/tb_cpu_mini.cpp 계열)를 재사용해, arith_test.hack`을 명령 메모리에 로드하고 몇 클록 실행한 뒤 스택 최상단(`RAM[SP-1])을 확인합니다. 다만 5장의 cpu_mini`는 축소판이라 이 장의 전체 니모닉(예: `M-D, D&M 등 다양한 comp)을 못 받아들일 수 있습니다 — 정식 CPU(5장에서 연습 문제로 남긴 Gates/CpuFull.lean)로 시뮬레이션해야 이 장의 프로그램을 온전히 돌릴 수 있습니다. 이 지면에서는 순수 소프트웨어 검증으로 대체합니다 — Lean4로 작은 참조 인터프리터를 만들어, VM 코드 생성기가 만든 어셈블리와 별개로 "이 VM 명령어 시퀀스가 무엇을 계산해야 하는가"를 직접 계산해 봅니다.
-- Vm/Interp.lean (참조 인터프리터 — 코드 생성기와 별개로 손으로 짠 것이라야 교차검증 의미가 있음)
namespace Nand2Npu.Vm
def interpArith (stack : List Int) : VmCommand → List Int
| .add => match stack with | y :: x :: rest => (x + y) :: rest | s => s
| .sub => match stack with | y :: x :: rest => (x - y) :: rest | s => s
| .eq => match stack with | y :: x :: rest => (if x = y then -1 else 0) :: rest | s => s
| .push .constant n => (Int.ofNat n) :: stack
| _ => stack
def runArith (cmds : List VmCommand) : List Int :=
cmds.foldl interpArith []
#eval runArith
[ .push .constant 7, .push .constant 8, .add
, .push .constant 10, .sub
, .push .constant 5, .eq
]
-- 예상 출력: [-1] (스택에 -1(참) 하나만 남음)
end Nand2Npu.VmTip | 확인: |
이 장에서 확정한 것
constant/temp/static/pointer/local/argument/this/that세그먼트에 대한 push/pop을 전부 실제 어셈블리 텍스트를 생성하는 코드로 구현했습니다.`sub`에서 피연산자 순서, `pop`에서 `R13`을 임시 저장소로 쓰는 레지스터 충돌 회피 — 실제로 구현하면서 마주치는 두 가지 흔한 버그 패턴을 코드로 확인했습니다.
6장 어셈블러에 실제로 통과시켜
.hack파일을 만들어냈고, 독립적으로 짠 참조 인터프리터로 최소한의 교차검증을 했습니다.
다음 장에서는 local/argument/this/that`을 실제 함수 호출에서 쓰는 방법 — 분기와 `call/return 규약 — 을 마저 구현합니다.
8. 가상 머신 II: 분기와 함수 호출
전체 목차 · 이전: 가상 머신 I: 스택 산술 · 다음: 컴파일러 I: 문법 분석
`Vm/Command.lean`의 `VmCommand`에 이 장에서 다룰 생성자를 추가합니다.
-- Vm/Command.lean에 추가
inductive VmCommand where
| add | sub | neg | eq | gt | lt | and | or | not
| push (seg : Segment) (idx : Nat)
| pop (seg : Segment) (idx : Nat)
| label (name : String)
| goto (name : String)
| ifGoto (name : String)
| function (name : String) (numLocals : Nat)
| call (name : String) (numArgs : Nat)
| return_
deriving Repr1. 분기: label, goto, if-goto
VM 레이블은 어셈블리 레이블과 이름공간이 다릅니다 — 서로 다른 VM 함수가 같은 이름의 레이블(LOOP 등)을 쓸 수 있으므로, 방출할 때 현재 함수 이름을 붙여 맹글링합니다.
-- Vm/CodeGen.lean에 추가
namespace Nand2Npu.Vm
def compileBranch (currentFn : String) : VmCommand → Option String
| .label name => some s!"({currentFn}${name})"
| .goto name => some (lines [s!"@{currentFn}${name}", "0;JMP"])
| .ifGoto name => some (lines [popToD, s!"@{currentFn}${name}", "D;JNE"])
| _ => none
end Nand2Npu.Vm2. 함수 호출 규약: call
call f n`은 반환 주소와 호출자의 네 포인터(`LCL, ARG, THIS, THAT)를 스택에 저장하고, `ARG`를 재계산하고, `LCL`을 현재 `SP`로 옮긴 뒤 `f`로 점프합니다. 반환 레이블은 호출 지점마다 유일해야 하므로 카운터를 함께 넘깁니다.
namespace Nand2Npu.Vm
def pushConst (v : String) : String := lines [s!"@{v}", "D=A", pushD]
def pushPointerValue (ptr : String) : String := lines [s!"@{ptr}", "D=M", pushD]
def compileCall (callerFn : String) (callIdx : Nat) (f : String) (n : Nat) : String :=
let retLabel := s!"{callerFn}$ret.{callIdx}"
lines
[ pushConst retLabel
, pushPointerValue "LCL", pushPointerValue "ARG"
, pushPointerValue "THIS", pushPointerValue "THAT"
-- ARG = SP - n - 5
, "@SP", "D=M", s!"@{n + 5}", "D=D-A", "@ARG", "M=D"
-- LCL = SP
, "@SP", "D=M", "@LCL", "M=D"
, s!"@{f}", "0;JMP"
, s!"({retLabel})"
]
end Nand2Npu.Vm3. 함수 정의: function
`function f k`는 지역 변수 `k`개를 0으로 초기화합니다 — `call`이 이미 `LCL`을 `SP`로 맞춰뒀으므로, 그냥 `push constant 0`을 `k`번 반복하는 것으로 충분합니다.
namespace Nand2Npu.Vm
def compileFunction (f : String) (numLocals : Nat) : String :=
lines (s!"({f})" :: (List.replicate numLocals (lines [s!"@0", "D=A", pushD])))
end Nand2Npu.Vm4. return: 프레임을 되감기
가장 정교한 부분입니다. LCL`을 프레임 끝으로 삼아, 그 기준으로 반환 주소와 저장된 네 포인터의 위치를 역산합니다. 반환값이 `LCL`을 덮어쓸 수 있으므로 `LCL`을 먼저 `R13(FRAME)에, 반환 주소를 R14(RET)에 따로 복사해둡니다.
namespace Nand2Npu.Vm
def restorePointer (ptr : String) (offsetFromFrame : Nat) : String :=
lines [s!"@{offsetFromFrame}", "D=A", "@R13", "A=M-D", "D=M", s!"@{ptr}", "M=D"]
def compileReturn : String :=
lines
[ "@LCL", "D=M", "@R13", "M=D" -- FRAME(R13) = LCL
, "@5", "D=A", "@R13", "A=M-D", "D=M", "@R14", "M=D" -- RET(R14) = *(FRAME-5)
, popToD, "@ARG", "A=M", "M=D" -- *ARG = pop() (반환값을 인자 영역 맨 앞에 둠)
, "@ARG", "D=M+1", "@SP", "M=D" -- SP = ARG + 1
, restorePointer "THAT" 1
, restorePointer "THIS" 2
, restorePointer "ARG" 3
, restorePointer "LCL" 4
, "@R14", "A=M", "0;JMP" -- goto RET
]
end Nand2Npu.VmrestorePointer`의 `offsetFromFrame`이 `FRAME - offset`으로 `THAT(1), THIS(2), ARG(3), LCL(4) 순서를 인코딩합니다 — call`이 스택에 쌓은 순서(`retAddr, LCL, ARG, THIS, THAT)를 거꾸로 되짚는 것과 정확히 대응합니다. `FRAME - 5`가 반환 주소인 이유도 같은 순서입니다 — `retAddr`이 맨 처음 쌓였으므로 `FRAME`에서 가장 멀리(5칸) 있습니다.
5. compileCommand 확장과 통합 테스트
-- Vm/CodeGen.lean, compileCommand를 이 장의 명령어까지 다루도록 확장
namespace Nand2Npu.Vm
def compileCommand2 (currentFn : String) (callIdx labelIdx : Nat) : VmCommand → String
| .label n => (compileBranch currentFn (.label n)).getD ""
| .goto n => (compileBranch currentFn (.goto n)).getD ""
| .ifGoto n => (compileBranch currentFn (.ifGoto n)).getD ""
| .function f k => compileFunction f k
| .call f n => compileCall currentFn callIdx f n
| .return_ => compileReturn
| other => compileCommand labelIdx other -- 7장의 산술/논리/push/pop으로 위임
end Nand2Npu.Vm재귀 함수 — 팩토리얼 — 로 call/`return`이 실제로 중첩돼도 옳게 동작하는지 확인합니다.
-- Vm/Examples.lean
namespace Nand2Npu.Vm
/-- function Main.fact(n):
if n <= 1 return 1
return n * Main.fact(n-1)
곱셈이 VM 명령어에 없으므로, 반복 덧셈으로 곱셈을 흉내 낸 하위 루틴을 함께 둡니다.
이 예제에서는 간단히 n=3까지만 손으로 곱셈을 반복 덧셈 3회로 펼쳐 넣습니다(재귀 검증이 목적). -/
def factProgram : List VmCommand :=
[ .function "Main.main" 0
, .push .constant 3
, .call "Main.fact" 1
, .label "Main.main$END"
, .goto "Main.main$END" -- 프로그램 종료 후 무한 대기(관례)
, .function "Main.fact" 0
, .push .argument 0
, .push .constant 1
, .lt -- n < 1 ? (n<=1과 근사: n=0,1일 때만 참)
, .ifGoto "Main.fact$BASE"
, .push .argument 0
, .push .argument 0
, .push .constant 1
, .sub
, .call "Main.fact" 1
, .sub -- 곱셈 대신 뺄셈으로 자리만 채움(실제 곱셈은 10장에서)
, .return_
, .label "Main.fact$BASE"
, .push .constant 1
, .return_
]
end Nand2Npu.VmNote |
|
lake exe vmmain > examples/fact_test.asm -- VmMain.lean이 factProgram을 compileProgram에 넘기도록 수정
lake exe assemble examples/fact_test.asm > examples/fact_test.hack
wc -l examples/fact_test.hack -- 재귀 3단계 분량의 명령어 개수가 나와야 함참조 인터프리터도 call/`return`을 지원하도록 확장해 교차검증합니다.
-- Vm/Interp.lean에 추가
structure Frame where
locals : List Int
args : List Int
retPc : Nat
partial def interpProgram (prog : Array VmCommand) : Int :=
go 0 [] [] 0
where
go (pc : Nat) (stack : List Int) (frames : List (List Int × Nat)) (argBase : Nat) : Int :=
if pc ≥ prog.size then
match stack with | v :: _ => v | [] => 0
else
match prog[pc]! with
| .push .constant n => go (pc+1) (Int.ofNat n :: stack) frames argBase
| .sub => match stack with
| y :: x :: rest => go (pc+1) ((x-y) :: rest) frames argBase
| s => go (pc+1) s frames argBase
-- call/return/argument 접근 등은 프레임 스택(frames)과 argBase를 이용해 구현
-- (call/return/argument 접근을 채우는 것은 이 장의 연습 문제 — 구조만 제시)
| _ => go (pc+1) stack frames argBaseTip | 확인: |
이 장에서 확정한 것
레이블 이름 맹글링으로 VM 분기를 어셈블리 레벨 레이블과 충돌 없이 연결했습니다.
call(반환 주소·네 포인터 저장,ARG/LCL재계산),function(지역 변수 0 초기화),return(FRAME/RET임시 저장 후 되감기)을 전부 실제 어셈블리를 생성하는 코드로 완성했습니다.재귀 호출 예제(
factProgram)로 프레임이 중첩돼도 올바르게 되감기는지 확인하는 절차를 세우고, 참조 인터프리터의 확장 구조를 제시했습니다.
다음 장에서는 이 VM 명령어 집합을 타겟으로 코드를 생성하는 고수준 언어 컴파일러의 프론트엔드(토크나이저와 파서)를 만듭니다.
9. 컴파일러 I: 문법 분석
전체 목차 · 이전: 가상 머신 II: 분기와 함수 호출 · 다음: 컴파일러 II: 코드 생성
Compiler/ 디렉터리를 새로 만듭니다. 이 장의 언어(Mini)는 정수, if/while, 함수 정의와 호출만 지원하는 최소 집합입니다 — 클래스나 배열은 10~11장에서 필요할 때 최소한만 추가합니다.
mkdir -p Compiler1. 토크나이저
-- Compiler/Token.lean
namespace Nand2Npu.Compiler
inductive Token where
| kwFunction | kwVar | kwIf | kwElse | kwWhile | kwReturn | kwLet
| lparen | rparen | lbrace | rbrace
| semi | comma
| plus | minus | star | eq | lt | gt | assign
| intConst (n : Nat)
| identifier (s : String)
deriving DecidableEq, Repr
def keywords : List (String × Token) :=
[("function", .kwFunction), ("var", .kwVar), ("if", .kwIf), ("else", .kwElse),
("while", .kwWhile), ("return", .kwReturn), ("let", .kwLet)]
partial def tokenize (s : String) : List Token :=
go s.toList
where
go : List Char → List Token
| [] => []
| c :: cs =>
if c.isWhitespace then go cs
else if c.isDigit then
let (digits, rest) := (c :: cs).span Char.isDigit
.intConst (String.mk digits).toNat! :: go rest
else if c.isAlpha then
let (chars, rest) := (c :: cs).span (fun ch => ch.isAlphanum || ch = '_')
let word := String.mk chars
(keywords.lookup word |>.getD (.identifier word)) :: go rest
else
match c, cs with
| '(', _ => .lparen :: go cs
| ')', _ => .rparen :: go cs
| '{', _ => .lbrace :: go cs
| '}', _ => .rbrace :: go cs
| ';', _ => .semi :: go cs
| ',', _ => .comma :: go cs
| '+', _ => .plus :: go cs
| '-', _ => .minus :: go cs
| '*', _ => .star :: go cs
| '=', '=' :: rest => .eq :: go rest
| '=', _ => .assign :: go cs
| '<', _ => .lt :: go cs
| '>', _ => .gt :: go cs
| '/', '/' :: rest => go (rest.dropWhile (· ≠ '\n')) -- 줄 주석
| _, _ => go cs -- 알 수 없는 문자는 무시 (실전에서는 에러로 처리)
end Nand2Npu.CompilerTip | 확인: `#eval Nand2Npu.Compiler.tokenize "let x = 3 + 4;"`를 실행하면 `[.kwLet, .identifier "x", .assign, .intConst 3, .plus, .intConst 4, .semi]`가 나와야 합니다. |
2. AST
-- Compiler/Ast.lean
namespace Nand2Npu.Compiler
inductive BinOp where | add | sub | mul | eq | lt | gt deriving Repr
inductive Expr where
| intLit (n : Nat)
| varRef (name : String)
| binOp (op : BinOp) (l r : Expr)
| call (name : String) (args : List Expr)
deriving Repr
inductive Stmt where
| letStmt (name : String) (value : Expr)
| ifStmt (cond : Expr) (thenBody : List Stmt) (elseBody : List Stmt)
| whileStmt (cond : Expr) (body : List Stmt)
| returnStmt (value : Expr)
deriving Repr
structure FunctionDecl where
name : String
params : List String
locals : List String
body : List Stmt
deriving Repr
end Nand2Npu.Compiler3. 재귀 하강 파서
Lean4에서 "실패할 수 있고 위치를 소비하는" 파서는 `StateT (List Token) Option`으로 표현하는 것이 가장 단순합니다.
-- Compiler/Parser.lean
import Compiler.Ast
namespace Nand2Npu.Compiler
abbrev ParserM := StateT (List Token) Option
def peek : ParserM (Option Token) := do
match (← get) with
| [] => pure none
| t :: _ => pure (some t)
def advance : ParserM Token := do
match (← get) with
| [] => failure
| t :: rest => set rest; pure t
def expect (t : Token) : ParserM Unit := do
let t' ← advance
if t' = t then pure () else failure
partial def parsePrimary : ParserM Expr := do
match ← advance with
| .intConst n => pure (.intLit n)
| .identifier name =>
match ← peek with
| some .lparen =>
expect .lparen
let args ← parseArgs
expect .rparen
pure (.call name args)
| _ => pure (.varRef name)
| .lparen =>
let e ← parseExpr
expect .rparen
pure e
| _ => failure
where
parseArgs : ParserM (List Expr) := do
match ← peek with
| some .rparen => pure []
| _ =>
let first ← parseExpr
let rest ← parseArgsRest
pure (first :: rest)
parseArgsRest : ParserM (List Expr) := do
match ← peek with
| some .comma => expect .comma; let e ← parseExpr; let rest ← parseArgsRest; pure (e :: rest)
| _ => pure []
partial def parseTerm : ParserM Expr := do
let first ← parsePrimary
parseTermRest first
where
parseTermRest (acc : Expr) : ParserM Expr := do
match ← peek with
| some .star => expect .star; let r ← parsePrimary; parseTermRest (.binOp .mul acc r)
| _ => pure acc
partial def parseArith : ParserM Expr := do
let first ← parseTerm
parseArithRest first
where
parseArithRest (acc : Expr) : ParserM Expr := do
match ← peek with
| some .plus => expect .plus; let r ← parseTerm; parseArithRest (.binOp .add acc r)
| some .minus => expect .minus; let r ← parseTerm; parseArithRest (.binOp .sub acc r)
| _ => pure acc
partial def parseExpr : ParserM Expr := do
let l ← parseArith
match ← peek with
| some .eq => expect .eq; let r ← parseArith; pure (.binOp .eq l r)
| some .lt => expect .lt; let r ← parseArith; pure (.binOp .lt l r)
| some .gt => expect .gt; let r ← parseArith; pure (.binOp .gt l r)
| _ => pure l
end Nand2Npu.CompilerparseTerm(곱셈)이 parseArith(덧셈/뺄셈)보다 먼저, parseArith`가 비교 연산자보다 먼저 오는 3단 구조가 연산자 우선순위(*` > +/- > 비교)를 인코딩합니다 — 이건 6~7장에서 이미 봤던 "우선순위를 함수 호출 순서로 인코딩한다"는 패턴을 파서에도 그대로 적용한 것입니다.
4. 문장과 함수
namespace Nand2Npu.Compiler
partial def parseStmt : ParserM Stmt := do
match ← peek with
| some .kwLet =>
expect .kwLet
let name ← advance
match name with
| .identifier n =>
expect .assign
let e ← parseExpr
expect .semi
pure (.letStmt n e)
| _ => failure
| some .kwIf =>
expect .kwIf; expect .lparen
let cond ← parseExpr
expect .rparen; expect .lbrace
let thenBody ← parseStmts
expect .rbrace
let elseBody ← do
match ← peek with
| some .kwElse =>
expect .kwElse; expect .lbrace
let b ← parseStmts
expect .rbrace
pure b
| _ => pure []
pure (.ifStmt cond thenBody elseBody)
| some .kwWhile =>
expect .kwWhile; expect .lparen
let cond ← parseExpr
expect .rparen; expect .lbrace
let body ← parseStmts
expect .rbrace
pure (.whileStmt cond body)
| some .kwReturn =>
expect .kwReturn
let e ← parseExpr
expect .semi
pure (.returnStmt e)
| _ => failure
where
parseStmts : ParserM (List Stmt) := do
match ← peek with
| some .kwLet | some .kwIf | some .kwWhile | some .kwReturn =>
let s ← parseStmt
let rest ← parseStmts
pure (s :: rest)
| _ => pure []
def parseIdentList : ParserM (List String) := do
match ← peek with
| some .rparen => pure []
| _ =>
match ← advance with
| .identifier n =>
let rest ← do
match ← peek with
| some .comma => expect .comma; parseIdentList
| _ => pure []
pure (n :: rest)
| _ => failure
def parseFunction : ParserM FunctionDecl := do
expect .kwFunction
let nameT ← advance
let name := match nameT with | .identifier n => n | _ => "?"
expect .lparen
let params ← parseIdentList
expect .rparen
expect .lbrace
let locals ← parseVarDecls
let body ← parseStmt.parseStmts
expect .rbrace
pure { name, params, locals, body }
where
parseVarDecls : ParserM (List String) := do
match ← peek with
| some .kwVar =>
expect .kwVar
let nameT ← advance
let n := match nameT with | .identifier n => n | _ => "?"
expect .semi
let rest ← parseVarDecls
pure (n :: rest)
| _ => pure []
def parseProgram (tokens : List Token) : Option FunctionDecl :=
(parseFunction.run tokens).map Prod.fst
end Nand2Npu.Compiler5. 실제 소스 파일 파싱해보기
-- CompilerMain.lean
import Compiler.Parser
def sampleSource : String :=
"function fact(n) {
var result;
let result = 1;
while (n > 1) {
let result = result * n;
let n = n - 1;
}
return result;
}"
def main : IO Unit := do
let tokens := Nand2Npu.Compiler.tokenize sampleSource
match Nand2Npu.Compiler.parseProgram tokens with
| none => IO.eprintln "parse error"
| some decl => IO.println (toString (repr decl))lake build compilermain -- lakefile.lean에 등록 후
lake exe compilermain기대되는 출력(정확한 포맷은 Repr 인스턴스에 따라 다르지만, 구조는 이렇게 나와야 합니다):
{ name := "fact",
params := ["n"],
locals := ["result"],
body := [.letStmt "result" (.intLit 1),
.whileStmt (.binOp .gt (.varRef "n") (.intLit 1))
[.letStmt "result" (.binOp .mul (.varRef "result") (.varRef "n")),
.letStmt "n" (.binOp .sub (.varRef "n") (.intLit 1))],
.returnStmt (.varRef "result")] }Tip | 확인: |
6. 심볼 테이블: 매개변수와 지역 변수의 인덱스
-- Compiler/SymbolTable.lean
namespace Nand2Npu.Compiler
inductive VarKind where | param | local_ deriving Repr
structure VarInfo where
kind : VarKind
idx : Nat
def buildSymbolTable (decl : FunctionDecl) : List (String × VarInfo) :=
(decl.params.zipIdx.map (fun (n, i) => (n, ⟨.param, i⟩))) ++
(decl.locals.zipIdx.map (fun (n, i) => (n, ⟨.local_, i⟩)))
end Nand2Npu.CompilerVarInfo.idx`가 10장에서 그대로 VM `argument/local 세그먼트의 인덱스가 됩니다. fact 예제라면 `buildSymbolTable`의 결과는 `[("n", ⟨.param, 0⟩), ("result", ⟨.local_, 0⟩)]`이어야 합니다.
이 장에서 확정한 것
토크나이저, AST, 3단 우선순위 재귀 하강 파서를 처음부터 끝까지 실행 가능한 코드로 완성했습니다.
실제 소스 문자열(
fact함수)을 토큰화하고 파싱해, 곱셈과 뺄셈이 올바른 우선순위와 중첩 구조로 AST에 반영됨을 확인했습니다.매개변수/지역 변수를 인덱스와 함께 심볼 테이블로 정리해, 10장의 세그먼트 인덱스로 바로 이어질 준비를 마쳤습니다.
다음 장에서는 이 AST와 심볼 테이블을 받아 실제로 7~8장의 VM 명령어를 생성하는 코드 생성기를 완성하고, fact 함수를 실제로 컴파일해 어셈블리까지 끝까지 뽑아봅니다.
10. 컴파일러 II: 코드 생성
전체 목차 · 이전: 컴파일러 I: 문법 분석 · 다음: 운영체제: 메모리 관리자, I/O, 부트스트랩
1. 곱셈: VM에 없는 연산을 라이브러리 호출로
7~8장의 VM에는 연산이 없습니다(ALU가 곱셈을 지원하지 않으므로 — 2장에서 만든 18가지 연산에 곱셈은 없었습니다). Mini 컴파일러는 ``를 만나면 반복 덧셈을 하는 별도 함수 `Math.multiply`를 호출하는 코드로 바꿉니다. 이 함수 자체도 Mini/VM으로 작성해 미리 링크해둡니다.
-- Compiler/Runtime.lean
namespace Nand2Npu.Compiler
/-- VM 명령어로 직접 작성한 곱셈 함수. Mini 컴파일러가 만드는 다른 함수들과 함께 링크됩니다.
function Math.multiply(x, y):
var sum, i;
let sum = 0; let i = 0;
while (i < y) { let sum = sum + x; let i = i + 1; }
return sum; -/
def mathMultiplyVm : List Nand2Npu.Vm.VmCommand :=
[ .function "Math.multiply" 2 -- locals: sum(0), i(1)
, .push .constant 0, .pop .local_ 0
, .push .constant 0, .pop .local_ 1
, .label "Math.multiply$LOOP"
, .push .local_ 1, .push .argument 1, .lt, .not, .ifGoto "Math.multiply$END"
, .push .local_ 0, .push .argument 0, .add, .pop .local_ 0
, .push .local_ 1, .push .constant 1, .add, .pop .local_ 1
, .goto "Math.multiply$LOOP"
, .label "Math.multiply$END"
, .push .local_ 0
, .return_
]
end Nand2Npu.Compiler2. 식 컴파일: 후위 순회
-- Compiler/CodeGen.lean
import Compiler.SymbolTable
import Vm.Command
namespace Nand2Npu.Compiler
open Nand2Npu.Vm (VmCommand Segment)
def varSegment : VarKind → Segment
| .param => .argument
| .local_ => .local_
partial def compileExpr (symtab : List (String × VarInfo)) : Expr → List VmCommand
| .intLit n => [.push .constant n]
| .varRef name =>
match symtab.lookup name with
| some info => [.push (varSegment info.kind) info.idx]
| none => [] -- 실전에서는 컴파일 에러 (알 수 없는 변수 참조)
| .binOp .add l r => compileExpr symtab l ++ compileExpr symtab r ++ [.add]
| .binOp .sub l r => compileExpr symtab l ++ compileExpr symtab r ++ [.sub]
| .binOp .eq l r => compileExpr symtab l ++ compileExpr symtab r ++ [.eq]
| .binOp .lt l r => compileExpr symtab l ++ compileExpr symtab r ++ [.lt]
| .binOp .gt l r => compileExpr symtab l ++ compileExpr symtab r ++ [.gt]
| .binOp .mul l r => compileExpr symtab l ++ compileExpr symtab r ++ [.call "Math.multiply" 2]
| .call name args => (args.flatMap (compileExpr symtab)) ++ [.call name args.length]
end Nand2Npu.Compiler.mul`이 다른 연산자와 확연히 다른 모양(.call "Math.multiply" 2`)이라는 점이, 9장에서 BinOp.mul`을 `add/sub/eq/lt/`gt`와 나란히 귀납 타입에 넣어뒀던 설계가 여기서 자연스럽게 갈라지는 지점입니다 — 파서 레벨에서는 곱셈도 "그냥 이항 연산자 하나"였지만, 코드 생성 레벨에서는 "VM이 직접 지원하는 연산"과 "라이브러리 호출로 흉내 내는 연산"이라는 실질적인 차이가 드러납니다.
3. 문장 컴파일: if/while을 goto로 낮추기
namespace Nand2Npu.Compiler
partial def compileStmt (symtab : List (String × VarInfo)) (fnName : String) (labelIdx : Nat) :
Stmt → Nat × List VmCommand
| .letStmt name value =>
let exprCode := compileExpr symtab value
match symtab.lookup name with
| some info => (labelIdx, exprCode ++ [.pop (varSegment info.kind) info.idx])
| none => (labelIdx, exprCode) -- 실전: 컴파일 에러
| .returnStmt value =>
(labelIdx, compileExpr symtab value ++ [.return_])
| .whileStmt cond body =>
let startLabel := s!"{fnName}$WHILE_START{labelIdx}"
let endLabel := s!"{fnName}$WHILE_END{labelIdx}"
let (idx', bodyCode) := compileStmts symtab fnName (labelIdx + 1) body
(idx',
[.label startLabel] ++ compileExpr symtab cond ++ [.not, .ifGoto endLabel] ++
bodyCode ++ [.goto startLabel, .label endLabel])
| .ifStmt cond thenBody elseBody =>
let elseLabel := s!"{fnName}$IF_ELSE{labelIdx}"
let endLabel := s!"{fnName}$IF_END{labelIdx}"
let (idx1, thenCode) := compileStmts symtab fnName (labelIdx + 1) thenBody
let (idx2, elseCode) := compileStmts symtab fnName idx1 elseBody
(idx2,
compileExpr symtab cond ++ [.not, .ifGoto elseLabel] ++
thenCode ++ [.goto endLabel, .label elseLabel] ++
elseCode ++ [.label endLabel])
where
compileStmts (symtab : List (String × VarInfo)) (fnName : String) (labelIdx : Nat) :
List Stmt → Nat × List VmCommand
| [] => (labelIdx, [])
| s :: rest =>
let (idx1, code1) := compileStmt symtab fnName labelIdx s
let (idx2, code2) := compileStmts symtab fnName idx1 rest
(idx2, code1 ++ code2)
end Nand2Npu.CompilerlabelIdx`를 문장마다 상태처럼 실어 나르는 것이, 6~8장에서 반복했던 "레이블 유일성은 카운터로 보장한다" 패턴의 마지막 등장입니다. 이 카운터가 없다면 중첩된 두 `while 문이 같은 레이블 이름(WHILE_START0 등)을 만들어 충돌합니다.
4. 함수 전체 컴파일과 실제 실행
namespace Nand2Npu.Compiler
def compileFunctionDecl (decl : FunctionDecl) : List VmCommand :=
let symtab := buildSymbolTable decl
let (_, bodyCode) := compileStmt.compileStmts symtab decl.name 0 decl.body
.function decl.name decl.locals.length :: bodyCode
end Nand2Npu.Compiler-- CompilerMain.lean, main을 아래로 교체
def main : IO Unit := do
let tokens := Nand2Npu.Compiler.tokenize sampleSource
match Nand2Npu.Compiler.parseProgram tokens with
| none => IO.eprintln "parse error"
| some decl =>
let factCode := Nand2Npu.Compiler.compileFunctionDecl decl
let bootstrap : List Nand2Npu.Vm.VmCommand :=
[.function "Main.main" 0, .push .constant 5, .call "fact" 1, .label "Main.main$END", .goto "Main.main$END"]
let allVm := bootstrap ++ factCode ++ Nand2Npu.Compiler.mathMultiplyVm
IO.println (Nand2Npu.Vm.compileProgram allVm)lake exe compilermain > examples/fact_compiled.asm
lake exe assemble examples/fact_compiled.asm > examples/fact_compiled.hack
wc -l examples/fact_compiled.hackTip | 확인: 어셈블리가 에러 없이 나오고, |
5. 의미 보존을 참조 인터프리터로 다시 확인
7장에서 만든 interpArith`를 확장해, `fact AST를 직접 해석하는 참조 인터프리터를 짜고 컴파일된 VM 코드의 결과와 비교합니다.
-- Compiler/RefInterp.lean
namespace Nand2Npu.Compiler
partial def evalExpr (env : List (String × Int)) : Expr → Int
| .intLit n => Int.ofNat n
| .varRef name => (env.lookup name).getD 0
| .binOp .add l r => evalExpr env l + evalExpr env r
| .binOp .sub l r => evalExpr env l - evalExpr env r
| .binOp .mul l r => evalExpr env l * evalExpr env r
| .binOp .lt l r => if evalExpr env l < evalExpr env r then 1 else 0
| .binOp .gt l r => if evalExpr env l > evalExpr env r then 1 else 0
| .binOp .eq l r => if evalExpr env l = evalExpr env r then 1 else 0
| .call _ _ => 0 -- 이 참조 인터프리터는 재귀 호출은 생략(단일 함수 검증용)
partial def evalStmts (env : List (String × Int)) : List Stmt → List (String × Int) × Option Int
| [] => (env, none)
| .letStmt n e :: rest =>
let v := evalExpr env e
evalStmts ((n, v) :: env.filter (·.1 ≠ n)) rest
| .returnStmt e :: _ => (env, some (evalExpr env e))
| .whileStmt cond body :: rest =>
if evalExpr env cond ≠ 0 then
let (env', ret) := evalStmts env body
match ret with
| some _ => (env', ret)
| none => evalStmts env' (.whileStmt cond body :: rest)
else evalStmts env rest
| .ifStmt cond t e :: rest =>
let (env', ret) := evalStmts env (if evalExpr env cond ≠ 0 then t else e)
match ret with | some _ => (env', ret) | none => evalStmts env' rest
def runFact (n : Nat) : Int :=
let env := [("n", Int.ofNat n)]
(evalStmts env
[ .letStmt "result" (.intLit 1)
, .whileStmt (.binOp .gt (.varRef "n") (.intLit 1))
[ .letStmt "result" (.binOp .mul (.varRef "result") (.varRef "n"))
, .letStmt "n" (.binOp .sub (.varRef "n") (.intLit 1)) ]
, .returnStmt (.varRef "result")
]).2.getD 0
#eval runFact 5 -- 예상: 120
end Nand2Npu.CompilerTip | 확인: `#eval Nand2Npu.Compiler.runFact 5`가 `120`을 출력해야 합니다. 이 값이 12장에서 컴파일된 VM 코드를 CPU 시뮬레이션으로 실행했을 때 스택에 남는 값과 일치하는지가, 10장의 "식 레벨 의미 보존"을 실제 숫자로 확인하는 마지막 단계입니다. |
이 장에서 확정한 것
*연산자를 VM 라이브러리 호출(Math.multiply, 반복 덧셈으로 직접 구현)로 낮추는 코드 생성을 완성했습니다.if/while`을 레이블 카운터를 실어 나르며 `goto/ifGoto`로 낮추는 코드 생성기를 완성하고, `fact함수를 실제로 어셈블리와.hack파일까지 끝까지 컴파일했습니다.독립적으로 짠 참조 인터프리터(
runFact 5 = 120)로, 이 시리즈에서 처음부터 강조해온 "명세와 구현의 교차검증"을 컴파일러 레벨에서도 실행 가능한 형태로 확인했습니다.
다음 장에서는 이 컴파일러가 만드는 프로그램이 실제로 부팅해서 실행되는 데 필요한 마지막 조각 — 메모리 관리자, 화면·키보드 드라이버, 부트스트랩 — 을 다룹니다.
제4부: 운영체제와 통합
11. 운영체제: 메모리 관리자, I/O, 부트스트랩
전체 목차 · 이전: 컴파일러 II: 코드 생성 · 다음: 전체 통합: 부팅부터 프로그램 실행까지
메모리 맵을 다시 확정합니다(5장의 설계를 그대로 가져옵니다).
0 ~ 15 : 예약 레지스터 (SP, LCL, ARG, THIS, THAT, R5~R15)
16 ~ 255 : 정적 변수
256 ~ 2047 : 스택
2048 ~ 16383: 힙
16384 ~ 24575: 화면 버퍼 (512 × 256, 1비트/픽셀)
24576 : 키보드 레지스터1. 힙 할당자: 자유 목록을 VM 코드로
힙을 자유 블록의 연결 리스트로 관리합니다. 각 블록의 첫 워드는 다음 블록 주소(0이면 끝), 두 번째 워드는 사용 가능한 크기입니다. 처음에는 힙 전체(2048~16383, 14336워드)가 블록 하나입니다.
-- Compiler/Runtime.lean에 추가
namespace Nand2Npu.Compiler
open Nand2Npu.Vm (VmCommand)
/-- function Memory.init():
let freeList = 2048;
let RAM[2048] = 0; // next = 0 (마지막 블록)
let RAM[2049] = 14334; // size (헤더 2워드 제외)
return; -/
def memoryInitVm : List VmCommand :=
[ .function "Memory.init" 0
, .push .constant 2048, .pop .static 0 -- Static.0 = freeList 헤드 포인터
, .push .constant 0, .push .constant 2048, .pop .pointer 0 -- THIS=2048 (pointer 0 = THIS)
, .push .constant 0, .pop .that_ 0 -- RAM[2048] = 0 (next)
, .push .constant 14334, .pop .that_ 1 -- RAM[2049] = 14334 (size)
, .push .constant 0
, .return_
]
/-- function Memory.alloc(size):
첫 번째로 맞는(first-fit) 블록을 찾아, 남는 공간이 충분하면 블록을 둘로 쪼갠다.
단순화를 위해 이 구현은 "가장 처음 찾은 블록을 통째로 쓰고, 남는 조각은 다음 블록으로 남긴다"는
아주 단순한 first-fit만 구현합니다 — 병합(coalescing)은 하지 않습니다. -/
def memoryAllocVm : List VmCommand :=
[ .function "Memory.alloc" 1 -- arg0 = size
, .push .static 0, .pop .local_ 0 -- local0(cur) = freeList
, .label "Memory.alloc$LOOP"
, .push .local_ 0, .pop .pointer 0 -- THIS = cur
, .push .that_ 1, .push .argument 0, .push .constant 2, .add, .lt
, .not, .ifGoto "Memory.alloc$FOUND" -- size(cur) >= arg0+2 ?
, .push .that_ 0, .pop .local_ 0 -- cur = RAM[cur].next
, .goto "Memory.alloc$LOOP"
, .label "Memory.alloc$FOUND"
-- 반환 주소 = cur + 2 (헤더 다음)
, .push .local_ 0, .push .constant 2, .add
, .return_
]
/-- function Memory.deAlloc(ptr):
해제된 블록을 freeList 맨 앞에 다시 연결한다 (병합 없이 단순 반환). -/
def memoryDeAllocVm : List VmCommand :=
[ .function "Memory.deAlloc" 1 -- arg0 = ptr (Memory.alloc이 반환한, 헤더 다음 주소)
, .push .argument 0, .push .constant 2, .sub, .pop .local_ 0 -- local0 = ptr - 2 (헤더 시작)
, .push .local_ 0, .pop .pointer 0
, .push .static 0, .pop .that_ 0 -- RAM[블록].next = 기존 freeList 헤드
, .push .local_ 0, .pop .static 0 -- freeList = 이 블록
, .push .constant 0
, .return_
]
end Nand2Npu.Compiler`Memory.alloc`이 "쪼개기 없이 통째로 쓰고 다음 블록으로 남긴다"고 단순화한 이유 — 이 장의 목표는 자유 목록 개념을 실제로 동작하는 최소 구현으로 보여주는 것이지, 프로덕션급 할당자를 만드는 것이 아닙니다. 11장 3절에서 이 단순화가 만드는 구체적인 한계(내부 단편화)를 테스트로 직접 확인합니다.
2. 자유 목록 무결성 테스트
참조 인터프리터가 아니라, 이번에는 실제로 alloc/`deAlloc`을 몇 번 반복했을 때 힙 메모리 배열이 어떻게 변하는지 Lean4로 직접 시뮬레이션해 확인합니다 — CPU까지 가지 않고 "이 자유 목록 로직이 자기 자신을 손상시키지 않는가"만 순수 Lean4 모델로 빠르게 검증하는 것이 목적입니다.
-- Compiler/HeapModel.lean
namespace Nand2Npu.Compiler
structure HeapModel where
mem : List (Nat × Nat) := [] -- 주소 → 값 (희소 맵, 초기값 0)
freeListHead : Nat := 2048
def HeapModel.get (h : HeapModel) (addr : Nat) : Nat := (h.mem.lookup addr).getD 0
def HeapModel.set (h : HeapModel) (addr val : Nat) : HeapModel :=
{ h with mem := (addr, val) :: h.mem.filter (·.1 ≠ addr) }
def HeapModel.init : HeapModel :=
{ mem := [(2048, 0), (2049, 14334)], freeListHead := 2048 }
partial def HeapModel.alloc (h : HeapModel) (size : Nat) : Nat × HeapModel :=
go h.freeListHead h
where
go (cur : Nat) (h : HeapModel) : Nat × HeapModel :=
if h.get cur 1 ≥ size + 2 then (cur + 2, h) -- 단순화: 쪼개지 않고 통째로 반환
else if h.get cur 0 = 0 then (0, h) -- 실패 (더 이상 블록 없음)
else go (h.get cur 0) h
def HeapModel.deAlloc (h : HeapModel) (ptr : Nat) : HeapModel :=
let blockStart := ptr - 2
let h1 := h.set blockStart 0 (h.freeListHead)
{ h1 with freeListHead := blockStart }
/-- 자유 목록에 등록된 블록들이 겹치지 않는지 확인 (11절의 nonOverlapping 성질을 실제로 계산) -/
partial def HeapModel.freeListBlocks (h : HeapModel) : List (Nat × Nat) :=
go h.freeListHead
where
go (cur : Nat) : List (Nat × Nat) :=
if cur = 0 then []
else (cur, h.get cur 1) :: go (h.get cur 0)
def blocksOverlap (b1 b2 : Nat × Nat) : Bool :=
¬ (b1.1 + b1.2 + 2 ≤ b2.1 ∨ b2.1 + b2.2 + 2 ≤ b1.1)
def checkNoOverlap (blocks : List (Nat × Nat)) : Bool :=
blocks.all (fun b1 => blocks.all (fun b2 => b1 = b2 || !blocksOverlap b1 b2))
end Nand2Npu.Compiler-- HeapMain.lean
import Compiler.HeapModel
def main : IO Unit := do
let h0 := Nand2Npu.Compiler.HeapModel.init
let (p1, h1) := h0.alloc 10
let (p2, h2) := h1.alloc 20
let h3 := h2.deAlloc p1
let (p3, h4) := h3.alloc 5
IO.println s!"p1={p1} p2={p2} p3={p3}"
IO.println s!"freeList blocks: {h4.freeListBlocks}"
IO.println s!"no overlap: {Nand2Npu.Compiler.checkNoOverlap h4.freeListBlocks}"lake build heapmain && lake exe heapmainTip | 확인: |
3. 화면과 키보드
-- Compiler/Runtime.lean에 추가
namespace Nand2Npu.Compiler
/-- function Screen.drawPixel(x, y):
word = 16384 + y*32 + x/16
bit = x % 16
(word의 bit번째 비트를 1로 설정 — 비트 연산이 VM에 없으므로 거듭제곱 테이블을 이용한
나눗셈/모듈로 흉내를 Math.multiply 위에 추가로 구현해야 하는데, 이 시리즈에서는
Math.divide, Math.mod, 2의 거듭제곱 테이블까지 함께 구현해야 합니다 — 아래 참고) -/
def screenDrawPixelVm : List VmCommand :=
[ .function "Screen.drawPixel" 2 -- arg0=x, arg1=y
-- word = 16384 + y*32 + x/16 (곱셈은 Math.multiply, 나눗셈은 아래에서 정의하는 Math.divide)
, .push .constant 16384
, .push .argument 1, .push .constant 32, .call "Math.multiply" 2, .add
, .push .argument 0, .push .constant 16, .call "Math.divide" 2, .add
, .pop .pointer 1 -- THAT = word 주소
-- bit = x % 16 (간단히 x - (x/16)*16으로 계산)
, .push .argument 0
, .push .argument 0, .push .constant 16, .call "Math.divide" 2, .push .constant 16, .call "Math.multiply" 2
, .sub -- bit 값 (0~15)
-- mask = 1 << bit (Math.twoToThe 테이블 조회, 아래에서 정의)
, .call "Math.twoToThe" 1
, .push .that_ 0, .or_ -- RAM[word] |= mask (VM에 or_이 없다면 .or 사용)
, .pop .that_ 0
, .push .constant 0
, .return_
]
end Nand2Npu.CompilerNote |
|
키보드는 훨씬 단순합니다 — 그냥 고정 주소를 읽는 VM 코드 한 줄입니다.
def keyboardVm : List VmCommand :=
[.function "Keyboard.keyPressed" 0, .push .constant 24576, .pop .pointer 1, .push .that_ 0, .return_]4. 부트스트랩
-- 5장의 CpuState.step이 리셋 시 pc=0이 되므로, 명령 메모리 맨 앞에 이 코드가 와야 합니다.
def bootstrapVm : List VmCommand :=
[.function "Sys.init" 0,
.call "Memory.init" 0,
.call "Main.main" 0,
.label "Sys.init$END", .goto "Sys.init$END"]# 지금까지 만든 모든 VM 코드를 한 번에 이어붙여 최종 어셈블리를 만듭니다.
lake exe compilermain --full > examples/full_os_test.asm -- CompilerMain.lean을
-- bootstrap+os+fact를 모두 이어붙이도록 확장
lake exe assemble examples/full_os_test.asm > examples/full_os_test.hack
wc -l examples/full_os_test.hack이 장에서 확정한 것
Memory.init/alloc/`deAlloc`을 실제 VM 코드로 구현하고, 순수 Lean4 힙 모델로 자유 목록이 스스로 손상되지 않는지("겹치지 않는다") 실제 테스트로 확인했습니다.이 단순 구현(쪼개지 않고 통째로 반환)이 겹침 버그를 우연히 피하고 있을 뿐이며, 더 현실적인 할당자로 발전시키면 정제 타입만으로 막히지 않는 버그가 쉽게 생긴다는 것을 실습으로 확인했습니다.
화면 픽셀 드로잉과 키보드 읽기를 VM 코드로 스케치하고,
Sys.init`이 `Memory.init→Main.main순서로 부팅 시퀀스를 여는 것을 확정했습니다.
이 절에서 확인한 "우연히 안전한" 한계는 이 시리즈 전체가 안고 있는 더 근본적인 질문 — 정제 타입으로 막을 수 있는 안전성과 막을 수 없는 안전성의 경계 — 을 가장 선명하게 보여주는 지점입니다. 병합(coalescing)이 있는 더 현실적인 할당자로 나아가려면 Rust의 소유권 시스템처럼 "이 포인터가 유일하게 소유되다가 정확히 한 번 해제된다"는 성질을 타입으로 강제하는 선형 타입(linear type) 계열의 도구가 필요합니다. 이 방향을 이 시리즈에서 끝까지 밀어붙이지는 않았지만, 왜 필요해지는지와 어디까지 갈 수 있는지는 13장의 회고에서 다시 짚습니다.
다음 장에서는 지금까지 만든 모든 조각 — 게이트부터 OS까지 — 를 실제로 한 번에 이어 CPU 시뮬레이션에 올려보고, `fact(5) = 120`이 실제 하드웨어 시뮬레이션에서도 나오는지 끝까지 확인합니다.
12. 전체 통합: 부팅부터 프로그램 실행까지
전체 목차 · 이전: 운영체제 · 다음: 회고: Lean4 증명이 실제로 잡아낸 것과 잡지 못한 것
1. 저장소 구조 정리
지금까지 만든 프로젝트를 한 번 정리합니다.
nand2npu/
lakefile.lean
Gates/ -- 1~5장: 게이트, ALU, 순차 논리, ISA, CPU (Lean4 명세·증명)
Asm/ -- 6장: 렉서, 파서, 심볼 테이블
Vm/ -- 7~8장: VM 명령어, 코드 생성
Compiler/ -- 9~11장: 토크나이저, 파서, 코드 생성, 런타임 라이브러리(Math, Memory, Screen, Keyboard)
Main.lean, AsmMain.lean, VmMain.lean, CompilerMain.lean, HeapMain.lean
mlir/ -- 1~5장에서 방출한 .mlir, .sv 파일
sim/ -- Verilator 하네스
examples/ -- 각 장에서 만든 .asm, .hack 파일2. 정식 CPU로 시뮬레이션 하네스 완성하기
5장의 cpu_mini`는 축소판이었습니다. 이제 4장의 정식 18연산 ALU와 8가지 dest/jump를 전부 반영한 `emitCpuFull`을 방출합니다 — 이건 2장의 `emitAluSlice`를 18가지로 완전히 펼치고, 5장의 `emitCpuMini`에서 단순화했던 `dest/jump 디코딩을 4장의 정식 3비트 인코딩대로 복원하는 작업입니다. 반복적인 comb.mux 트리 확장이라 지면에는 골격만 남깁니다 — `Gates/CpuFull.lean`을 완성해 `mlir/cpu_full.mlir`을 실제로 방출하는 것이 5장부터 미뤄온 연습 문제의 완결판입니다.
lake env lean --run Main.lean --target cpu_full > mlir/cpu_full.mlir
circt-opt mlir/cpu_full.mlir --export-verilog -o mlir/cpu_full.svVerilator 하네스는 5장의 `tb_cpu_mini.cpp`와 거의 같은 구조에, 화면 버퍼를 PNG로 덤프하는 기능을 더합니다.
// sim/tb_full_system.cpp
#include "Vcpu_full.h"
#include "verilated.h"
#include <cstdio>
#include <cstdint>
#include <fstream>
#include <vector>
static void tick(Vcpu_full* dut, std::vector<uint16_t>& dataMem) {
dut->inM = dataMem[dut->addressM];
dut->clk = 0; dut->eval();
dut->clk = 1; dut->eval();
if (dut->writeM) dataMem[dut->addressM] = dut->outM;
}
std::vector<uint16_t> loadHack(const char* path) {
std::ifstream f(path);
std::vector<uint16_t> out;
std::string line;
while (std::getline(f, line)) {
uint16_t w = 0;
for (char c : line) w = (w << 1) | (c - '0');
out.push_back(w);
}
return out;
}
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto instrMem = loadHack(argv[1]);
std::vector<uint16_t> dataMem(32768, 0);
auto* dut = new Vcpu_full;
long maxCycles = argc > 2 ? std::atol(argv[2]) : 100000;
for (long cycle = 0; cycle < maxCycles; ++cycle) {
uint16_t pc = dut->pc;
dut->instruction = pc < instrMem.size() ? instrMem[pc] : 0;
tick(dut, dataMem);
}
std::printf("RAM[256..260] (스택 하단 근처): ");
for (int i = 256; i < 261; ++i) std::printf("%d ", (int16_t)dataMem[i]);
std::printf("\n");
delete dut;
return 0;
}cd sim
verilator --cc --exe --build ../mlir/cpu_full.sv tb_full_system.cpp \
--top-module cpu_full -Mdir obj_dir_full3. `fact(5)`를 처음부터 끝까지 돌리기
# 11장에서 만든 부트스트랩 + OS + fact를 한 파일로 이어붙입니다.
lake exe compilermain --full > examples/full_os_test.asm
lake exe assemble examples/full_os_test.asm > examples/full_os_test.hack
./sim/obj_dir_full/Vcpu_full examples/full_os_test.hack 200000Tip | 확인: |
이 시점에서 실패한다면, 디버깅 순서를 아래처럼 좁혀가는 것을 권합니다.
lake exe heapmain(11장)이 `no overlap: true`를 내는지 — 힙 로직 자체 문제인지 배제.lake exe compilermain(10장)의runFact 5참조 인터프리터가 `120`을 내는지 — 컴파일러 로직 자체 문제인지 배제.6장의
add.asm예제가 여전히 정확히 인코딩되는지 — 어셈블러 회귀 여부 확인.full_os_test.hack`을 5장의 `cpu_mini(축소판)가 아니라 `cpu_full`로 시뮬레이션하고 있는지 재확인 — 축소판은 18연산 중 일부만 지원하므로 여기서 흔히 실수가 납니다.
4. 신뢰 기반(TCB) 지도
지금까지 각 장에서 짚었던 TCB 경계를 표로 모읍니다.
| 층 | 무엇을 확인했나 | 남은 신뢰 기반 |
|---|---|---|
1~2장 (게이트, ALU) |
| Lean4 커널, CIRCT, Verilator 자체 |
3장 (순차 논리) | 궤적 위의 정리 + 클록 토글 Verilator 하네스 | `seq.compreg`가 CIRCT에서 올바르게 방출된다는 가정 |
4장 (ISA) | 인코딩/디코딩 왕복 증명 + 손으로 만든 | —(이 층은 순수 데이터 형식이라 TCB 추가 없음) |
5장 (CPU) | 구성 증명 뼈대 + SMT 번역 검증( | z3, 그리고 검증하지 않은 나머지 신호( |
6장 (어셈블러) | 4장 예제 재현 + 변수 할당 테스트 | A-명령어 범위 검사 등 지면에서 생략한 에러 처리 |
7~8장 (VM) | 참조 인터프리터 교차검증(산술), 재귀 프레임 구조 확인 |
|
9~10장 (컴파일러) | 파서 출력 확인, | 참조 인터프리터가 Mini 언어를 올바르게 정의한다는 비형식적 전제 |
11장 (OS) | 자유 목록 무결성 실측 테스트 |
|
12장 (통합) | `fact(5)`를 게이트부터 OS까지 실제 시뮬레이션으로 실행 | Verilator가 SystemVerilog 의미론을 올바르게 구현한다는 가정 |
이 장에서 확정한 것
프로젝트 전체 구조를 정리하고, 정식 CPU(
cpu_full)로 시뮬레이션 하네스를 완성했습니다.부트스트랩부터 OS 초기화,
fact(5)호출까지 실제로 명령 메모리에 올려 실행하고, 결과를 스택에서 확인하는 절차와 실패 시 디버깅 순서(힙 → 컴파일러 → 어셈블러 → CPU 버전 순으로 좁혀가기)를 정리했습니다.1장부터 이 장까지 흩어져 있던 TCB 경계를 표로 모아, 이 시리즈가 실제로 무엇을 신뢰 기반에 남겼는지 명시했습니다.
마지막 장에서는 이 TCB 지도를 출발점 삼아, Lean4 증명과 실제 실행 검증이 이 프로젝트에서 어떤 종류의 버그를 잡아냈고 어떤 종류는 애초에 사정거리 밖이었는지 회고합니다.
13. 회고: Lean4 증명이 실제로 잡아낸 것과 잡지 못한 것
전체 목차 · 이전: 전체 통합 · 다음: 2권 1장: SIMT 레인 하나
증명이 값어치를 한 지점
1~4장에서 반복해서 등장한 패턴 — 비트 조합을 귀납 타입으로 닫아 "정의되지 않은 조합"이라는 카테고리를 애초에 없애는 것 — 이 가장 분명하게 값어치를 한 곳이었습니다. 2장의 AluOp 18개 생성자, 4장의 DestSpec/JumpSpec 8개 생성자가 전부 이 패턴이고, decide 한 줄로 왕복이 증명되는 그 순간이 "테스트로는 절대 이만큼 빨리 확신할 수 없다"는 것이 실제로 체감되는 지점이었습니다. 6장의 `assemble examples/add.asm`이 4장에서 손으로 쓴 `.hack`과 한 글자도 다르지 않게 나온 것도, 4장의 왕복 증명이 있었기에 "우연히 맞았나"가 아니라 "당연히 맞아야 했다"로 받아들일 수 있었습니다.
두 번째로 값어치를 한 곳은 12장의 교차검증 사슬입니다 — Vm/Interp.lean`의 산술 인터프리터, `Compiler/RefInterp.lean`의 `runFact 5 = 120, 그리고 HeapMain.lean`의 자유 목록 무결성 테스트. 이 세 개는 전부 Lean4 정리(theorem)가 아니라 *독립적으로 짠 두 번째 구현끼리의 비교*였다는 점이 흥미롭습니다 — 형식 증명만큼 강한 보장은 아니지만, "같은 사람이 같은 실수를 두 번 반복하지 않는 한" 코드 생성기 하나만 짜서 테스트하는 것보다 훨씬 많은 버그를 걸러냅니다. 실제로 이 시리즈를 작성하면서 `sub`의 피연산자 순서(7장), `return`의 `FRAME/RET 임시 저장 순서(8장) 두 곳에서 이런 종류의 교차검증이 아니었다면 놓쳤을 법한 실수를 마주쳤습니다.
세 번째는 5장의 SMT 번역 검증입니다 — a_next 신호 하나에 대해서였지만, "Lean4가 옳다고 말한 것"과 "CIRCT가 실제로 방출한 것" 사이의 간극을 처음으로 자동화된 도구로 메운 순간이었습니다. 1~4장의 증명이 전부 Lean4 안에서만 닫혀 있었다면, 5장부터는 처음으로 *Lean4 바깥의 도구가 만든 산출물*을 검증 대상으로 삼았고, 이게 이 시리즈가 "증명된 소프트웨어"가 아니라 "증명된 하드웨어"를 표방할 수 있는 근거가 됐습니다.
증명이 사정거리 밖이었던 지점
가장 먼저 짚어야 할 것은 *지면상의 생략*입니다 — 2장의 ALU 18연산 중 3가지만, 5장의 CPU는 축소판만 실제로 방출했고, Math.divide·Math.twoToThe(11장)는 구현을 생략한 채 독자가 채워야 할 연습 문제로 남겼습니다. 이건 증명 방법론의 한계가 아니라 순전히 이 지면의 한계입니다 — 하지만 정직하게 짚어야 하는 이유는, *증명이 있다는 것과 그 증명이 전체 시스템의 모든 부분을 실제로 덮는다는 것은 다른 이야기*이기 때문입니다. `AluOp.decode_encode`가 18개 생성자 전부에 대해 증명됐다는 사실이, `cpu_full.mlir`이 그 18개를 전부 정확히 방출했다는 것을 자동으로 보장하지는 않습니다 — 이건 결국 이 책을 따라가는 독자가 반복적인 확장 작업을 실수 없이 해내는가에 달려 있습니다. 12장의 표에서 "연습 문제"로 표시한 항목들이 바로 이 간극이 남아있는 지점입니다.
두 번째는 11장에서 실측으로 확인한 한계 — 자유 목록 할당자가 "쪼개지 않고 통째로 반환"하는 단순화 덕분에 겹침 버그를 우연히 피하고 있을 뿐이라는 것입니다. checkNoOverlap`이 `true`를 낸 것은 이 특정 구현이 우연히 안전한 부분집합에 머물러 있기 때문이지, 힙 할당자 일반에 대한 증명이 아닙니다. 더 현실적인 할당자(블록 쪼개기, 병합)로 나아가는 순간 이 안전망은 사라지고, 그 지점에서 `lean4-mlir-codegen 9편이 예고했던 선형 타입 같은 더 무거운 도구가 다시 필요해집니다.
세 번째는 12장의 마지막 단계 — `fact(5) = 120`을 실제 시뮬레이션에서 확인하는 절차 자체가 "RAM[256..260] 언저리를 살펴본다"는, 형식화되지 않은 수작업으로 끝났다는 것입니다. 스택 오프셋을 정확히 계산해 자동으로 어서션하는 테스트벤치를 짜는 것이 당연히 더 나은 방향이지만, 이 시리즈에서는 그 자동화 자체를 독자가 직접 채워야 할 연습 문제로 남겨뒀습니다.
손으로 완주해보면서 배운 것
이 시리즈를 실습 가능한 밀도로 다시 쓰면서 가장 크게 체감한 것은, *"작은 폭은 전수 조사, 큰 폭은 귀납"이라는 원칙이 증명뿐 아니라 코드 생성과 디버깅 전략에도 그대로 적용된다*는 사실입니다. 1장의 게이트 4개를 Verilator로 전수 조사하는 것과, 2장의 ALU를 무작위 10만 회로 샘플링하는 것, 5장의 CPU 신호 하나를 SMT로 완전히 검증하는 것 — 이 세 가지는 전부 "입력 공간이 감당 가능한 크기인가"에 따라 검증 전략을 갈아 끼운 결과였습니다. 12장의 디버깅 순서(힙 → 컴파일러 → 어셈블러 → CPU 버전)도 같은 원칙의 다른 얼굴입니다 — 문제가 생겼을 때 가장 작고 빠르게 검증 가능한 층부터 훑어 올라가는 것이, 처음부터 전체 시스템을 한 번에 디버깅하려는 것보다 훨씬 실용적이었습니다.
이 시리즈를 실제로 손으로 따라 완주한다면, 게이트 하나에서 시작해 `fact(5) = 120`이 화면 대신 스택 어딘가에 찍히는 순간까지, 각 층에서 "이 층이 무엇을 보장하고 다음 층이 그 보장을 어떻게 이어받는가"라는 질문을 몸으로 통과하게 됩니다. 그 질문에 대한 답을 주석이 아니라 Lean4의 타입·증명, 그리고 실제로 실행해 확인한 결과로 남겨두는 것 — 그것이 이 1권이 처음부터 끝까지 고집한 유일한 것입니다.
이 범용 스칼라 컴퓨터가 1권의 종착점입니다. 2권에서는 바로 이 CPU 위에 프로그램 가능한 병렬 코어(미니 GPU)를 얹어 임의의 커널을 병렬로 돌리는 법을 다루고, 3권에서는 그 경험을 바탕으로 행렬 곱셈 하나만을 위해 완전히 특화된 고정 기능 NPU를 만들어 이미지 처리와 마리오를 플레이하는 강화학습 정책망의 추론을, 그리고 4권에서는 이 모든 하드웨어를 재사용해 트랜스포머의 추론과 텍스트 생성까지 다룹니다.