Exec-yoo-ting the machine. We are exec-yoo-ting the machine.
Chris Pressey
11 months ago
23 | 23 |
state' <- writeAddr state addr' value
|
24 | 24 |
return state'
|
25 | 25 |
|
26 | |
run s = s
|
|
26 |
applyInstr :: State -> Instruction -> IO State
|
|
27 |
applyInstr state (Mov dest src) = do
|
|
28 |
value <- getValue state src
|
|
29 |
state' <- setValue state dest value
|
|
30 |
return state'
|
|
31 |
|
|
32 |
nth :: [a] -> Integer -> Maybe a
|
|
33 |
nth [] _ = Nothing
|
|
34 |
nth (x:xs) 0 = Just x
|
|
35 |
nth (x:xs) n = nth xs (n-1)
|
|
36 |
|
|
37 |
step :: State -> IO (Maybe State)
|
|
38 |
step state@State{ pc=pc, prog=prog } =
|
|
39 |
case nth prog pc of
|
|
40 |
Just instr -> do
|
|
41 |
state' <- applyInstr state instr
|
|
42 |
return $ Just state'{ pc=pc+1 }
|
|
43 |
Nothing ->
|
|
44 |
return Nothing
|
|
45 |
|
|
46 |
run :: State -> IO State
|
|
47 |
run state = do
|
|
48 |
result <- step state
|
|
49 |
case result of
|
|
50 |
Just state' ->
|
|
51 |
run state'
|
|
52 |
Nothing ->
|
|
53 |
return state
|
|
54 |
|
|
55 |
loadAndRun s =
|
|
56 |
let
|
|
57 |
prog = [Mov (Direct 0) (Immediate 0)] -- TODO parse s
|
|
58 |
state = initState prog
|
|
59 |
in
|
|
60 |
run state
|
23 | 23 |
} deriving (Show, Ord, Eq)
|
24 | 24 |
|
25 | 25 |
|
|
26 |
initState :: [Instruction] -> State
|
|
27 |
initState prog =
|
|
28 |
State{
|
|
29 |
pc=0,
|
|
30 |
mem=Map.empty,
|
|
31 |
prog=prog,
|
|
32 |
saved=Nothing
|
|
33 |
}
|
|
34 |
|
26 | 35 |
readMem mem addr = Map.findWithDefault 0 addr mem
|
27 | 36 |
writeMem mem addr value = Map.insert addr value mem
|
28 | |
|
29 | 37 |
|
30 | 38 |
beginTransaction :: State -> State
|
31 | 39 |
beginTransaction state@State{} =
|
11 | 11 |
case args of
|
12 | 12 |
["run", fileName] -> do
|
13 | 13 |
text <- readFile fileName
|
14 | |
putStrLn $ show $ reverse $ Machine.run text
|
|
14 |
result <- Machine.loadAndRun text
|
|
15 |
putStrLn $ show $ result
|
15 | 16 |
return ()
|
16 | 17 |
_ -> do
|
17 | 18 |
abortWith "Usage: zowie run <carriage-program-text-filename>"
|