All is one-op instructions (save push). Code in memory (this will allow compilation)

This commit is contained in:
2025-06-05 14:22:12 -05:00
parent 11eae06995
commit 679b53d76e
3 changed files with 204 additions and 137 deletions

View File

@@ -13,21 +13,22 @@
inst-obj
(error (format #f "could not find instruction ~a" inst))))
(define (instruction-size inst)
(case (instruction-type (lookup-instruction inst))
[(i j) 5]
[(o) 1]))
(define instruction? pair?)
(define label? (compose not instruction?))
(define label? (compose not pair?))
(define (variable? x)
(and (pair? x) (eq? (car x) 'variable)))
(define (instruction? x)
(and (not (label? x))
(not (variable? x))))
(define (find-labels inst-seq n)
(cond
[(null? inst-seq) '()]
[(label? (car inst-seq))
(acons (car inst-seq) n (find-labels (cdr inst-seq) n))]
[(variable? (car inst-seq))
(acons (cadar inst-seq) n (find-labels (cdr inst-seq) (+ n 4)))]
[else
(find-labels (cdr inst-seq) (+ n (instruction-size (caar inst-seq))))]))
(find-labels (cdr inst-seq) (if (eq? (caar inst-seq) 'push) (+ n 5) (+ n 1)))]))
(define (write-word word)
(define bv (make-bytevector 4))
@@ -37,16 +38,20 @@
(define (assemble inst-seq port)
(with-output-to-port port
(lambda ()
(define labels (find-labels inst-seq 0))
(define labels (find-labels inst-seq 1))
(let loop ([seq inst-seq])
(cond
[(null? seq) '()]
[(label? (car seq)) (loop (cdr seq))]
[(variable? (car seq))
(write-word (caddar seq))
(loop (cdr seq))]
[else
(let* [(inst (car seq))
(inst-obj (lookup-instruction (car inst)))]
(write-u8 (instruction-code inst-obj))
(case (instruction-type inst-obj)
[(i) (write-word (cadr inst))]
[(j) (write-word (assq-ref labels (cadr inst)))])
(when (eq? (car inst) 'push)
(if (number? (cadr inst))
(write-word (cadr inst))
(write-word (assq-ref labels (cadr inst)))))
(loop (cdr seq)))])))))