git @ Cat's Eye Technologies Turmac / 2afd38a
Add Language.Turmac.Simulator module, deprecating IRInterpreter. Chris Pressey 2 months ago
3 changed file(s) with 49 addition(s) and 7 deletion(s). Raw diff Collapse all Expand all
00 module Language.Turmac.IRInterpreter where
1
2 --
3 -- Note: this module is currently unused.
4 --
15
26 import Data.Map (Map)
37 import qualified Data.Map as Map
0 module Language.Turmac.Simulator where
1
2 import Language.Turmac.Model
3
4 -- | Single step of TM execution
5 step :: [TMRule] -> Configuration -> Configuration
6 step rules st@(Configuration tape state halted)
7 | halted = st -- Don't continue if halted
8 | otherwise = case findRule rules state (readSymbol tape) of
9 Just (_, _, newSym, newState, dir) ->
10 Configuration
11 (moveInDir dir (writeSymbol newSym tape))
12 (if newState == "H" then state else newState)
13 (newState == "H")
14 Nothing -> error $ "No rules for state " ++ show state ++
15 " and symbol " ++ show (readSymbol tape)
16
17 -- | Find matching rule for current state and symbol
18 findRule :: [TMRule] -> StateId -> Symbol -> Maybe TMRule
19 findRule rules state sym =
20 case [r | r@(s, sym', _, _, _) <- rules, s == state, sym' == sym] of
21 [] -> Nothing
22 (r:_) -> Just r
23
24 -- | Move tape in given direction
25 moveInDir :: Direction -> Tape -> Tape
26 moveInDir (-1) = moveLeft
27 moveInDir 1 = moveRight
28 moveInDir d = error $ "Invalid direction: " ++ show d
29
30 -- | Run TM until it halts, return history of configurations and final state
31 simulate :: [TMRule] -> Configuration -> ([Configuration], Configuration)
32 simulate rules config = go [] config
33 where
34 go history st@(Configuration _ _ True) =
35 (reverse (st:history), st)
36 go history st =
37 go (st:history) (step rules st)
38
39 -- | Run TM until it halts, return only final configuration
40 execute :: [TMRule] -> Configuration -> Configuration
41 execute rules config = snd $ simulate rules config
1010 import Language.Turmac.IR
1111 import Language.Turmac.Parser
1212 import Language.Turmac.Analyzer (isComplete)
13 import Language.Turmac.IRInterpreter
13 import Language.Turmac.Simulator
14 --import Language.Turmac.IRInterpreter
1415 import Language.Turmac.IRCompiler (buildProgram)
1516 import Language.Turmac.GenTape
1617 import Language.Turmac.Backend.Python
8889 case parse (checkComplete flags) turmacText of
8990 Right tmRules ->
9091 let
91 prog = buildProgram tmRules
9292 config = initConfigurationWithInput (initialTape flags)
93 (configs, finalConfig) = simulate prog config
93 (configs, finalConfig) = simulate tmRules config
9494 in do
9595 case trace flags of
9696 True -> do
101101 return ()
102102 putStrLn $ (show finalConfig) ++ ", Halted: " ++ show (tmHalted finalConfig)
103103 exitWith ExitSuccess
104
105 Left errMsg -> do
106 putStrLn $ "Error parsing input file: " ++ errMsg
107 exitWith $ ExitFailure 1
108104
109105 ["compile", fileName] -> do
110106 turmacText <- readFile fileName