← SEARCHABLE ARCHIVE
Nand2Tetris · 2026-05-22

Nand2Tetris — 11장

Jack 컴파일러

INTERACTIVE READING MODE →

# Jack Compiler
# 입력: .jack 파일
# 출력: .vm 파일
# 범위: symbol table + VM code generation
# 동작:
# class/static/field 심볼과 subroutine/local/argument 심볼을 나누어 관리하고,
# let, do, return, expression을 VM 명령어로 변환함


class SymbolTable:
    def __init__(self):
        self.class_scope = {}
        self.subroutine_scope = {}
        self.counts = {"static": 0, "field": 0, "argument": 0, "var": 0}

    def start_subroutine(self):
        self.subroutine_scope = {}
        self.counts["argument"] = 0
        self.counts["var"] = 0

    def define(self, name, type_name, kind):
        index = self.counts[kind]
        self.counts[kind] += 1

        symbol = {
            "type": type_name,
            "kind": kind,
            "index": index,
        }

        if kind in ("static", "field"):
            self.class_scope[name] = symbol
        else:
            self.subroutine_scope[name] = symbol

    def var_count(self, kind):
        return self.counts[kind]

    def find(self, name):
        if name in self.subroutine_scope:
            return self.subroutine_scope[name]
        return self.class_scope.get(name)


class VMWriter:
    SEGMENT = {
        "static": "static",
        "field": "this",
        "argument": "argument",
        "var": "local",
    }

    def __init__(self):
        self.lines = []

    def write_push(self, segment, index):
        self.lines.append(f"push {segment} {index}")

    def write_pop(self, segment, index):
        self.lines.append(f"pop {segment} {index}")

    def write_arithmetic(self, command):
        self.lines.append(command)

    def write_label(self, label):
        self.lines.append(f"label {label}")

    def write_goto(self, label):
        self.lines.append(f"goto {label}")

    def write_if(self, label):
        self.lines.append(f"if-goto {label}")

    def write_call(self, name, arg_count):
        self.lines.append(f"call {name} {arg_count}")

    def write_function(self, name, local_count):
        self.lines.append(f"function {name} {local_count}")

    def write_return(self):
        self.lines.append("return")


class CompilerExample:
    def __init__(self):
        self.symbols = SymbolTable()
        self.vm = VMWriter()

    def write_variable_push(self, name):
        symbol = self.symbols.find(name)
        segment = VMWriter.SEGMENT[symbol["kind"]]
        self.vm.write_push(segment, symbol["index"])

    def write_variable_pop(self, name):
        symbol = self.symbols.find(name)
        segment = VMWriter.SEGMENT[symbol["kind"]]
        self.vm.write_pop(segment, symbol["index"])

    def compile_let_simple(self, name):
        # let name = expression;
        # expression 결과가 stack top에 있다고 가정하고 변수 위치로 pop
        self.write_variable_pop(name)

    def compile_do_call(self, full_name, arg_count):
        # do 함수호출; 은 반환값을 사용하지 않으므로 temp 0으로 버림
        self.vm.write_call(full_name, arg_count)
        self.vm.write_pop("temp", 0)

    def compile_return_void(self):
        self.vm.write_push("constant", 0)
        self.vm.write_return()
// Jack 코드: let x = 10 + 20;
// VM 변환 예시
push constant 10
push constant 20
add
pop local 0
// Jack 코드: do Output.printInt(x);
// VM 변환 예시
push local 0
call Output.printInt 1
pop temp 0