Advertisement
Guest User

Bf interpreter

a guest
Jan 11th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 2.09 KB | None | 0 0
  1. ;;;No known bugs
  2. (defun simplify (code); code is a string
  3.   (loop with returncode = ""
  4.      for char across code
  5.      if (not (position char "><+-.,[]"))
  6.      do (progn)
  7.      else
  8.      do (setf returncode (concatenate 'string returncode (coerce `(,char) 'string)))
  9.      finally (return returncode)))
  10.  
  11. (defun matching-closing (code instruction-pointer)
  12.   (loop with counter = 0
  13.      for char from 0 to (1- (- (length code) instruction-pointer ))
  14.      when (equal (elt (subseq code instruction-pointer) char) #\[)
  15.      do (incf counter)
  16.      when (and (not (zerop counter)) (equal (elt (subseq code instruction-pointer) char) #\]))
  17.      do (decf counter)
  18.      when (and (zerop counter) (equal (elt (subseq code instruction-pointer) char) #\]))
  19.      return (+ instruction-pointer char)))
  20.  
  21. (defun main (code)
  22.   (setf code (simplify code))
  23.   (let ((memory (make-array (expt 10 5) :adjustable t :initial-element 0)) (data-pointer (/ (expt 10 5) 2)))
  24.     (loop with stack = '()
  25.        :for instruction-pointer from 0 :to (1- (length code)) :do
  26.      (case (elt code instruction-pointer)
  27.        (#\> (incf data-pointer))
  28.        (#\< (decf data-pointer))
  29.        (#\+ (incf (aref memory data-pointer)))
  30.        (#\- (decf (aref memory data-pointer)))
  31.        (#\. (princ (coerce  `(,(code-char (aref memory data-pointer))) 'string)))
  32.        (#\, (setf (aref memory data-pointer) (char-code (read-char))))
  33.        (#\[ (if (zerop (aref memory data-pointer))
  34.                 (setf instruction-pointer (matching-closing code instruction-pointer))
  35.                 (push instruction-pointer stack)))
  36.        (#\] (if (not (zerop (aref memory data-pointer)))
  37.                 (setf instruction-pointer (1- (pop stack)))
  38.                 (pop stack)))))))
  39.  
  40. (defun read-file (file) ; Just a simple function to read from a file and return all of it's contents as a string. Used to read bf programs from files.
  41.   (let ((return-string ""))
  42.     (with-open-file (stream file)
  43.       (loop :for line = (read-line stream nil 'foo)
  44.             :until (eq line 'foo)  
  45.             :do (setf return-string  (concatenate 'string return-string line))
  46.             :finally (return return-string)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement