-
-
Save cwvh/7297590 to your computer and use it in GitHub Desktop.
SSEM simulator in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE BangPatterns #-} | |
import Data.Array.IO | |
import Data.Array.Base | |
import Data.Bits | |
import Data.Int (Int32) | |
main = do | |
!inits <- return . map (fromIntegral . bin2signed) . lines =<< getContents | |
program <- newListArray (0,31) inits :: IO (IOUArray Int Int) | |
v <- ssem program | |
print v | |
where | |
bin2signed :: String -> Int32 | |
bin2signed = foldl (\n c -> 2*n + if c=='1' then 1 else 0) 0 | |
ssem stack = go stack 0 0 | |
where | |
go stack !acc !pc0 = do | |
let pc = pc0 + 1 | |
instr <- unsafeRead stack pc | |
let opcode = (instr `shiftR` 29) .&. 7 | |
operand = instr .&. 31 | |
v <- unsafeRead stack operand | |
case opcode of | |
0 -> go stack acc v | |
1 -> go stack acc (pc + v) | |
2 -> go stack (-v) pc | |
3 -> unsafeWrite stack operand acc >> go stack acc pc | |
4 -> go stack (acc - v) pc | |
6 -> go stack acc (pc + if acc < 0 then 1 else 0) | |
7 -> unsafeRead stack 27 >>= return | |
_ -> fail $ show opcode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment