Tiny compiler and VM
Posted on October 9, 2016
I’m working on a small toy language and vm in haskell, just for fun.
So far, I haven’t gotten far. I’ve started with the VM, which can currently add integers and print characters to stdout. This is what it looks like:
data Instr
= Push Int64 | Add | PutChar | Halt
deriving (Show, Eq)
type Stack = [Int64]
evalI :: Instr -> Stack -> IO Stack
evalI (Push i) s = pure $ i : s
evalI Add (y:x:s) = pure $ x + y : s
evalI PutChar (c:s) = putStr (show c) >> pure s
evalI Halt s = pure s
eval :: [Instr] -> Stack -> IO Stack
eval = flip $ foldM (flip evalI)
And it can be invoked like this:
main = eval [Push 1, Push 2, Add, PutChar, Halt] []
This will print the character ‘3’ to stdout.