Skip to content

Instantly share code, notes, and snippets.

@psilord
Created March 22, 2025 03:55
Show Gist options
  • Save psilord/e34c28bc781094c7e213b14b93255b6c to your computer and use it in GitHub Desktop.
Save psilord/e34c28bc781094c7e213b14b93255b6c to your computer and use it in GitHub Desktop.
(defparameter *inst* nil)
(defun ast->3ac-helper (ast)
(if (atom ast)
(cond
((numberp ast)
ast)
((symbolp ast)
ast)
(t
(error "oops, don't know what this is")))
(case (car ast)
((+ - * /)
(let ((name (gensym "T")))
(push `(,name = ,(ast->3ac-helper (cadr ast))
,(car ast)
,(ast->3ac-helper (caddr ast)))
*inst*)
name
)))))
(defun ast->3ac (ast)
(format t ";; New instruction stream for: ~A~%" ast)
(setf *inst* nil)
(ast->3ac-helper ast)
(setf *inst* (nreverse *inst*)))
(defun emit-3ac (3ac)
(format t "~{~A~%~}" 3ac))
;; run some of these
(emit-3ac (ast->3ac '(+ 1 2)))
(emit-3ac (ast->3ac '(+ 1 (+ 2 3))))
(emit-3ac (ast->3ac '(+ 1 (+ 2 (+ 3 4)))))
(emit-3ac (ast->3ac '(+ 1 (* 2 (- 3 (/ 4 5))))))
(emit-3ac (ast->3ac '(+ A B)))
(emit-3ac (ast->3ac '(+ A (+ B C))))
(emit-3ac (ast->3ac '(+ A (+ B (+ C D)))))
(emit-3ac (ast->3ac '(+ A (* B (- C (/ D E))))))
(emit-3ac (ast->3ac '(+ 1 B)))
(emit-3ac (ast->3ac '(+ 1 (+ 2 C))))
(emit-3ac (ast->3ac '(+ 1 (+ 2 (+ 3 D)))))
(emit-3ac (ast->3ac '(+ 1 (* 2 (- 3 (/ 4 E))))))
(emit-3ac (ast->3ac '(+ (- (* 1 2) (/ 3 4)) (+ (- 5 6) (- 7 8)))))
(emit-3ac (ast->3ac '(+ (+ (- 1 2) (- 3 4)) (+ (- 5 6) (- 7 8)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment