bfhs/lib/Backend/Interpreter.hs

64 lines
2.6 KiB
Haskell

module Backend.Interpreter (defaultInterpreter, Interpreter (Interpreter), Index, Size, getArray, modArray, getIndex, modIndex, getSize) where
import Backend
import Data.Array.Base (UArray, array, (!), (//))
import Data.List (singleton)
import Data.Word (Word16, Word8)
import Text.Printf (printf)
type Index = Word16
type Size = Word16
data Interpreter = Interpreter (UArray Index Word8) Index Size
instance BFExecutor Interpreter where
exec i = execStr i . singleton
execStr i str = _execStr (i, str)
where
_execStr (interpreter, (x : xs)) =
let (arr, index) = (getArray interpreter, getIndex interpreter)
in case (x) of
'>' -> _execStr (interpreter `modIndex` (flip mod 30000 . (+) 1), xs)
'<' -> _execStr (interpreter `modIndex` (flip mod 30000 . subtract 1), xs)
'+' -> _execStr (interpreter `modArray` (\a -> a // [(index, (arr ! index) + 1)]), xs)
'-' -> _execStr (interpreter `modArray` (\a -> a // [(index, (arr ! index) - 1)]), xs)
'.' -> (printf "%c" (word8ToChar (arr ! index))) >> _execStr (interpreter, xs)
',' -> getChar >>= (\c -> _execStr (interpreter `modArray` (\a -> a // [(index, charToWord8 c)]), xs))
'[' ->
if ((arr ! index) == 0)
then _execStr (interpreter, findMatching xs)
else _execStr (interpreter, xs) >>= (\inter -> _execStr (inter, x : xs))
']' -> return interpreter
_ -> _execStr (interpreter, xs)
_execStr (interpreter, []) = return interpreter
findMatching (x : xs) = case x of
'[' -> findMatching $ findMatching xs
']' -> xs
_ -> findMatching xs
findMatching [] = error "unclosed loop"
defaultInterpreter :: Interpreter
defaultInterpreter = Interpreter (array (0, 30000 - 1) [(i, 0) | i <- [0 .. 30000 - 1]]) (0 :: Index) (30000 :: Size)
charToWord8 :: Char -> Word8
charToWord8 = toEnum . fromEnum
word8ToChar :: Word8 -> Char
word8ToChar = toEnum . fromEnum
modArray :: Interpreter -> (UArray Index Word8 -> UArray Index Word8) -> Interpreter
modArray (Interpreter a b c) f = Interpreter (f a) b c
modIndex :: Interpreter -> (Index -> Index) -> Interpreter
modIndex (Interpreter a b c) f = Interpreter a (f b) c
getArray :: Interpreter -> UArray Index Word8
{-# INLINE getArray #-}
getArray (Interpreter arr _ _) = arr
getIndex :: Interpreter -> Index
{-# INLINE getIndex #-}
getIndex (Interpreter _ i _) = i
getSize :: Interpreter -> Size
{-# INLINE getSize #-}
getSize (Interpreter _ _ s) = s