debugging

This commit is contained in:
Peter McGoron 2024-11-19 09:47:46 -05:00
parent 9cf01c72c8
commit 3a716bb700
2 changed files with 20 additions and 5 deletions

View File

@ -1,13 +1,22 @@
# Brainfuck2Scheme # Brainfuck2Scheme
A simple compiler from Brainfuck to R5RS. The compiler will output a Scheme A simple compiler from Brainfuck to R5RS. The compiler will output a Scheme
list that is a lambda with two arguments: list that is a lambda with three arguments:
* `data`: The data vector. * `data`: The data vector.
* `dptr`: The initial data pointer. * `dptr`: The initial data pointer.
* `debugger`: Debugger function
To turn the list into an executable Scheme function, just give it to To turn the list into an executable Scheme function, just give it to
`eval`. `eval`. `(execute scheme len)` will run the Scheme code in `scheme`
with a data vector of length `len`.
This dialect of Brainfuck supports `#` to call the `debugger` procedure
with `data` and `dptr` as arguments.
Since Brainfuck programs become Scheme procedures, you can modularize
Brainfuck code and (ab)use the debugger for things like procedure calls
and foreign libraries.
## How It Works ## How It Works
@ -24,6 +33,7 @@ Data access brainfuck instructions are translated like
* `<` -> `(set! dptr (- dptr 1))` * `<` -> `(set! dptr (- dptr 1))`
* `.` -> `(display (vector-ref data dptr))` * `.` -> `(display (vector-ref data dptr))`
* `,` -> `(vector-set! data dptr (read-char))` * `,` -> `(vector-set! data dptr (read-char))`
* `#` -> `(debugger data dptr)`
Branches are trickier. Basically, all code that will be executed in a block Branches are trickier. Basically, all code that will be executed in a block
is in a lambda. Given `[code...]`, the `code...` will be compiled to a is in a lambda. Given `[code...]`, the `code...` will be compiled to a

View File

@ -44,6 +44,8 @@
((#\,) (compile (cdr lst) ((#\,) (compile (cdr lst)
(cons '(vector-set! data dptr (cons '(vector-set! data dptr
(char->integer (read-char))) ins))) (char->integer (read-char))) ins)))
((#\#) (compile (cdr lst)
(cons '(debugger data dptr) ins)))
((#\[) (let ((rest (compile (cdr lst) '()))) ((#\[) (let ((rest (compile (cdr lst) '())))
(if (not (pair? rest)) (if (not (pair? rest))
(error "unmatched [") (error "unmatched [")
@ -62,7 +64,7 @@
(else (compile (cdr lst) ins))))) (else (compile (cdr lst) ins)))))
(define (brainfuck->scheme str) (define (brainfuck->scheme str)
`(lambda (data dptr) `(lambda (data dptr debugger)
(,(compile (string->list str) '())))) (,(compile (string->list str) '()))))
(define (brainfuck->scheme-from-file filename) (define (brainfuck->scheme-from-file filename)
@ -74,5 +76,8 @@
str str
(loop (string-append str (read-line port))))))))) (loop (string-append str (read-line port)))))))))
(define (execute scheme) (define (execute scheme len)
((eval scheme) (make-vector 4096) 0)) ((eval scheme) (make-vector len) 0
(lambda (data dptr)
(display (list data dptr))
(newline))))