bf: parameterize mem size, use incmodf

i'm not sure why i thought incmodf was slower
This commit is contained in:
mehbark 2024-12-18 01:01:45 -05:00
parent 9784d97607
commit 3c32c92530

15
bf.lisp
View file

@ -3,12 +3,14 @@
(defmacro incmodf (place mod &optional (delta 1))
`(setf ,place (mod (+ ,place ,delta) ,mod)))
; TODO: ooo could totally gen from sym (e.g. '++-[]>)
; then i'd need some sort of var syntax ugh
(defpattern cmd (op val)
`(list ',op ,val))
; mandelbrot is about 5kb shorter with this :P
; zeroing-add gets us more
(defun optimize-loop (ins)
(match ins
((list (cmd inc _)) '(setf cell 0))
@ -50,29 +52,32 @@
(#\[ (put)
(let1 inner (comp-part port)
(push (or (optimize-loop inner)
`(loop until (zerop cell) do (progn ,@inner)))
`(loop until (zerop cell)
do (progn ,@inner)))
out))))
finally (put)
finally (return (nreverse out)))))
(defparameter mem-size 32768)
(defun comp (&optional (port *standard-input*))
(eval
`(lambda (&key (in *standard-input*) (out *standard-output*))
(declare (optimize (speed 3) (safety 0)))
(begin
(= mem (make-array 65536 :element-type '(unsigned-byte 8)))
(= mem (make-array ,mem-size :element-type '(unsigned-byte 8)))
(= mp 0)
(=sm cell (aref mem mp))
(=f inc (n) (setf cell (mod (+ cell n) 256)))
(=f minc (n) (setf mp (mod (+ mp n) 65536)))
(=f inc (n) (incmodf cell 256 n))
(=f minc (n) (incmodf mp ,mem-size n))
; TODO: fix
(=f get-byte () (setf cell (mod (char-code (read-char in nil #\null)) 256)))
(=f put-byte () (write-char (code-char cell) out))
(=f zeroing-add (rmove)
(incmodf (aref mem (mod (+ mp rmove) 65536)) 256 cell)
(incmodf (aref mem (mod (+ mp rmove) ,mem-size)) 256 cell)
(setf cell 0))
,@(comp-part port)