Permalink
Browse files

Add fibonacci sequence example/test

  • Loading branch information...
jaspervdj committed Apr 11, 2012
1 parent c642a34 commit f124ab140450422f938e096a877e3a82a86de71b
Showing with 42 additions and 6 deletions.
  1. +13 −0 examples/fib.s
  2. +2 −1 src/Emulator.hs
  3. +14 −4 src/Memory.hs
  4. +13 −1 tests/Examples.hs
View
@@ -0,0 +1,13 @@
; Fill memory with the fibonacci sequence. Source: reddit.
SET A, 1
SET B, 1
SET PEEK, 1
:loop ADD A, B ; A is now 2, B is still 1
SET PUSH, A
SET A, B
SET B, PEEK
IFG SP, 11 ; The original program had 10 here because that's how much
; space this program takes. Modified to be 11, so we run
; into a 0x0000 instruction when the program is finished,
; instead of our fibonacci numbers.
SET PC, loop
View
@@ -27,9 +27,10 @@ import Util
data Value
= Address Address
| Literal Word16
deriving (Eq)
instance Show Value where
show (Address a) = "[" ++ show a ++ "]"
show (Address a) = show a
show (Literal l) = prettifyWord16 l
-- | Load a program from a bytestring
View
@@ -17,8 +17,10 @@ import GHC.Prim
import GHC.ST (ST (..))
import GHC.Word (Word16 (..))
import Util
data Register = A | B | C | X | Y | Z | I | J
deriving (Bounded, Enum, Show)
deriving (Bounded, Enum, Eq, Show)
data Address
= Pc
@@ -27,13 +29,21 @@ data Address
| Cycles
| Register Register
| Ram Word16
deriving (Show)
deriving (Eq)
instance Show Address where
show Pc = "Pc"
show Sp = "Sp"
show O = "O"
show Cycles = "Cycles"
show (Register r) = show r
show (Ram r) = "[" ++ prettifyWord16 r ++ "]"
fromAddress :: Address -> Int
fromAddress Pc = 0x0
fromAddress Sp = 0x1
fromAddress O = 0x2
fromAddress Cycles = 0x4
fromAddress Cycles = 0x3
fromAddress (Register r) = 0x8 + fromEnum r
fromAddress (Ram r) = 0x16 + fromIntegral r
@@ -50,7 +60,7 @@ new = do
new' :: ST s (Memory s)
new' = ST $ \s1# ->
case newByteArray# (len# *# 2#) s1# of
case newAlignedPinnedByteArray# (len# *# 2#) 2# s1# of
(# s2#, marr# #) -> (# s2#, Memory marr# #)
where
!(I# len#) = 0x8 + 0x8 + 0x10000
View
@@ -9,7 +9,7 @@ import Data.List (sort)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, (@=?))
import Test.HUnit (Assertion, assert, (@=?))
import qualified Data.ByteString as B
import Assembler
@@ -38,6 +38,18 @@ tests = testGroup "Examples"
hi <- load $ Ram 0x1001
let sum' = (fromIntegral hi `shiftL` 16) + fromIntegral lo :: Int
return $ 0x12345678 + 0xaabbccdd @=? sum'
, testCase "fib.s" $ example "examples/fib.s" $ do
let fibs = 1 : 2 : zipWith (+) fibs (tail fibs)
addrs = [0xffff, 0xfffe .. 0x000c]
loop _ [] = return True
loop [] _ = return True
loop (f : fs) (a : as) = do
f' <- load $ Ram a
if f == f' then loop fs as else return False
return . assert =<< loop fibs addrs
]
example :: FilePath

0 comments on commit f124ab1

Please sign in to comment.