(Lispex)sicp.io
5.4 · 트리에서 명령으로

컴파일러는 일의 표현을 바꾼다.

작은 컴파일러는 표현식 트리를 나중에 별도 기계가 실행할 스택 명령으로 바꿀 수 있습니다.

생각해 볼 질문

표현식 트리는 어떻게 선형 명령열이 될까요?

  • Emit constant and arithmetic instructions from syntax data
  • Preserve operand order in stack code
  • Separate compilation from machine execution

compile emits the left operand code, then the right operand code, and finally one arithmetic instruction. Recursion flattens the nested expression into a linear list.

execute pushes constants. An arithmetic instruction pops the right and left values, combines them, and pushes the result. When no code remains, the stack top is the program value.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(begin
  (define (operator-instruction operator)
    (cond ((eq? operator '+) 'add)
          ((eq? operator '-) 'sub)
          ((eq? operator '*) 'mul)))
  (define (compile expression)
    (if (number? expression)
        (list (list 'const expression))
        (append (compile (cadr expression))
                (append (compile (caddr expression))
                        (list (operator-instruction (car expression)))))))
  (define (execute code stack)
    (if (null? code)
        (car stack)
        (let ((instruction (car code)))
          (if (pair? instruction)
              (execute (cdr code) (cons (cadr instruction) stack))
              (let ((right (car stack)) (left (cadr stack)))
                (execute
                  (cdr code)
                  (cons (cond ((eq? instruction 'add) (+ left right))
                              ((eq? instruction 'sub) (- left right))
                              ((eq? instruction 'mul) (* left right)))
                        (cddr stack))))))))
  (let ((code (compile '(+ (* 3 4) 5))))
    (list code (execute code '()))))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 1,088 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    The first program returns the five emitted instructions and the executed value 17.

    실행 흐름에서 볼 점

    Separate the recursive compile calls from the later execute calls. During execution, each instruction consumes code while changing the stack.

    직접 해보기

    힌트를 보기 전에 프로그램을 바꿔 보세요.

    Compile (+ 1 (* 2 (+ 3 4))). Write the instruction list before you execute it.

    힌트 하나 보기

    Each number emits const. Each compound expression emits its operator after both operands.