summaryrefslogtreecommitdiff
path: root/2-kyu/assembler-interpreter.hs
blob: b3887e6927d77d43b9609669e9944c070a256abc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
-- https://www.codewars.com/kata/58e61f3d8ff24f774400002c
module AssemblerInterpreter where

import Debug.Trace

import Data.Function((&))
import Data.Maybe (fromMaybe)
import Text.Parsec hiding (State)
import Text.Parsec.Char
import qualified Data.Map as M

import Control.Monad.Trans.Maybe
import Control.Monad.Trans.State
import Control.Monad.Trans.Class(lift)

type Parser = Parsec String ()

data Op =
  Mov | Inc | Dec | Add | Sub  | Mul | Div | Jmp | Cmp | Jne | Je |
  Jge | Jg  | Jle | Jl  | Call | Ret | Msg | End 
  deriving (Show)

stringP :: String -> Parser String
stringP str = try $ string str

opStrP :: Parser String
opStrP = choice $ map stringP [
  "mov", "inc", "dec", "add", "sub", "mul", "div", "jmp", "cmp", "jne",
  "je", "jge", "jg", "jle", "jl", "call", "ret", "msg", "end"]

opP :: Parser Op
opP = do
  s <- opStrP
  case s of
    "mov" -> return Mov
    "inc" -> return Inc
    "dec" -> return Dec
    "add" -> return Add
    "sub" -> return Sub
    "mul" -> return Mul
    "div" -> return Div
    "jmp" -> return Jmp
    "cmp" -> return Cmp
    "jne" -> return Jne
    "je"  -> return Je
    "jge" -> return Jge
    "jg"  -> return Jg
    "jle" -> return Jle
    "jl"  -> return Jl
    "call"-> return Call
    "ret" -> return Ret
    "msg" -> return Msg
    "end" -> return End

newtype Label = Label String
  deriving (Show)

inlineSpace :: Parser Char
inlineSpace = oneOf [' ', '\t'] 
inlineSpaces = skipMany $ oneOf [' ', '\t'] 

identifierP :: Parser String
identifierP = do
  notFollowedBy opStrP
  x <- letter <|> oneOf ['_']
  xs <- many (alphaNum <|> oneOf ['_'])
  return (x:xs)

labelP :: Parser Label
labelP = do
  id <- identifierP
  oneOf [':']
  return $ Label id

data Stmt = LabelStmt Label | InstrStmt Op [Arg]
  deriving (Show)

data Arg = IdentifierArg String | NumberArg Int | StringArg String
  deriving (Show)

argP :: Parser Arg
argP = do
  inlineSpaces
  let identifierArgP = IdentifierArg <$> identifierP
      numberP = do
        negSign <- optionMaybe $ char '-'
        let isNeg = case negSign of
              Just _ -> True
              Nothing -> False
        digits <- many1 digit
        let n :: Int = read digits 
        return $ NumberArg $ if isNeg then
          negate n
        else n
      stringP = do
        oneOf ['\''] :: Parser Char
        str <- many $ noneOf ['\'']
        oneOf ['\'']
        return $ StringArg str
  arg <- identifierArgP <|> numberP <|> stringP
  inlineSpaces
  return arg

stmtP :: Parser Stmt
stmtP = do
  let
    labelStmtP = LabelStmt <$> labelP
    argsP = do
      inlineSpaces
      oneOf [',']
      inlineSpaces
      arg <- argP
      inlineSpaces
      return arg
    instrStmtP = do
      op <- opP
      inlineSpaces
      marg <- optionMaybe argP
      args <- case marg of
        Just arg -> do
          targs <- many argsP
          return (arg:targs)
        Nothing -> return []
      return $ InstrStmt op args
  inlineSpaces
  stmt <- labelStmtP <|> instrStmtP
  inlineSpaces
  return stmt

commentP :: Parser ()
commentP = do
  oneOf [';']
  many $ noneOf ['\n']
  return ()

stmtLineP :: Parser [Stmt]
stmtLineP = do
  inlineSpaces
  ms <- optionMaybe stmtP
  inlineSpaces
  optional commentP
  inlineSpaces
  case ms of
    Just s -> return [s]
    Nothing -> return []

progP :: Parser [Stmt]
progP = do
  let newlineP = do
        newline :: Parser Char
        return (++)
  stmts <- chainl stmtLineP newlineP []
  spaces
  eof
  return stmts

processLabel :: [Stmt] -> ([Stmt], M.Map String Int)
processLabel stmts = go stmts [] M.empty 0 where
  go [] processed labelMap i = (reverse processed, labelMap)
  go (instr@(InstrStmt op args):xs) processed labelMap i =
    go xs (instr:processed) labelMap (i+1)
  go ((LabelStmt (Label ident)):xs) processed labelMap i =
    let newLabelMap = M.insert ident i labelMap 
    in
      go xs processed newLabelMap i

data MachineState = MachineState
  { machineRegisters :: M.Map String Int
  , machineStack :: [Int]
  , machineProgCnt :: Int
  , machineOutput :: Maybe String
  , machineProg :: [Stmt]
  , machineLabels :: M.Map String Int
  , machineCmpFlag :: Ordering
  , machineEnd :: Bool
  }
  deriving (Show)

type MachineM = MaybeT (State MachineState)

nextInstr :: MachineM ()
nextInstr = do
  ms <- lift get
  lift $ put (ms {machineProgCnt = machineProgCnt ms + 1})

fetchInstr :: MachineM (Maybe Stmt)
fetchInstr = do
  ms <- lift get
  let pc = machineProgCnt ms
      prog = machineProg ms
  if pc >= length prog || pc < 0 || machineEnd ms then return Nothing
  else return $ Just (prog !! pc)

setReg :: String -> Int -> MachineM ()
setReg r n = do
  ms <- lift get
  let regs = machineRegisters ms
  lift $ put ms {machineRegisters = M.insert r n regs}

getReg :: String -> MachineM Int
getReg r = do
  ms <- lift get
  let regs = machineRegisters ms
  case M.lookup r regs of
    Just n -> return n
    Nothing -> fail []

machinePush :: Int -> MachineM ()
machinePush n = do
  ms <- lift get
  let stack = machineStack ms
  lift $ put ms {machineStack = n:stack}

machinePop :: MachineM Int
machinePop = do
  ms <- lift get
  case machineStack ms of
    [] -> fail []
    (x:xs) -> do
      lift $ put ms {machineStack = xs}
      return x

execInstr :: Stmt -> MachineM ()
execInstr (InstrStmt op args) = decodeOp op args
execInstr _ = fail []

getResult :: MachineM String
getResult = do
  ms <- lift get
  if not (machineEnd ms) then fail []
  else case machineOutput ms of
    Nothing -> fail []
    Just msg -> return msg

runMachine :: MachineM String
runMachine = do
  ms <- lift get
  instr <- fetchInstr
  case instr of
    Nothing -> getResult
    Just stmt -> do execInstr stmt ; runMachine

execMov :: [Arg] -> MachineM ()
execMov [IdentifierArg reg, NumberArg n] = do
  setReg reg n
  nextInstr
execMov [IdentifierArg r1, IdentifierArg r2] = do
  n <- getReg r2
  setReg r1 n
  nextInstr
execMov _ = fail []

execMsg :: [Arg] -> MachineM ()
execMsg [] = fail []
execMsg args = go args "" where
  go [] msg = do
    ms <- lift get
    lift $ put ms { machineOutput = Just msg }
    nextInstr
  go ((NumberArg n):xs) msg = go  xs (msg ++ show n)
  go ((StringArg s):xs) msg = go xs (msg ++ s)
  go ((IdentifierArg reg):xs) msg = do
    n <- getReg reg
    go xs (msg ++ show n)

execEnd :: [Arg] -> MachineM ()
execEnd [] = do
  ms <- lift get
  lift $ put ms { machineEnd = True }
execEnd _ = fail []

execInc :: [Arg] -> MachineM()
execInc [IdentifierArg r] = do
  n <- getReg r
  setReg r (n+1)
  nextInstr
execInc _ = fail []

execDec :: [Arg] -> MachineM()
execDec [IdentifierArg r] = do
  n <- getReg r
  setReg r (n-1)
  nextInstr
execDec _ = fail []

execArithmetic :: (Int->Int->Int) -> [Arg] -> MachineM ()
execArithmetic op [IdentifierArg ra, IdentifierArg rb] = do
  n <- getReg rb
  execArithmetic op [IdentifierArg ra, NumberArg n]
execArithmetic op [IdentifierArg r, NumberArg n] = do
  x <- getReg r
  setReg r (op x n) 
  nextInstr
execArithmetic _ _ = fail []

execAdd = execArithmetic (+)
execSub = execArithmetic (-)
execMul = execArithmetic (*)
execDiv = execArithmetic div

machineGoto :: Int -> MachineM ()
machineGoto p = do
  ms <- lift get
  lift $ put ms {machineProgCnt = p}

execJmp :: [Arg] -> MachineM ()
execJmp [IdentifierArg lbl] = do
  ms <- lift get
  let labelMap = machineLabels ms
  case M.lookup lbl labelMap of
    Just pos -> machineGoto pos
    Nothing -> fail []
execJmp _ = fail []

execCmp :: [Arg] -> MachineM ()
execCmp [IdentifierArg r1, a2] = do
  n1 <- getReg r1
  execCmp [NumberArg n1, a2]
execCmp [a1, IdentifierArg r2] = do
  n2 <- getReg r2
  execCmp [a1, NumberArg n2]
execCmp [NumberArg n1, NumberArg n2] = do
  ms <- lift get
  lift $ put ms { machineCmpFlag = compare n1 n2 }
  nextInstr

execCondJmp :: [Ordering] -> [Arg] -> MachineM ()
execCondJmp conds [IdentifierArg lbl] = do
  flag <- machineCmpFlag <$> lift get
  if flag `elem` conds then execJmp [IdentifierArg lbl]
  else nextInstr
execCondJmp conds _ = fail []

execCall :: [Arg] -> MachineM ()
execCall [arg@(IdentifierArg lbl)] = do
  ms <- lift get
  let p = machineProgCnt ms + 1
  machinePush p
  execJmp [arg]

execRet :: [Arg] -> MachineM ()
execRet [] = do
  n <- machinePop
  machineGoto n
execRet _ = fail []

decodeOp :: Op -> [Arg] -> MachineM ()
decodeOp Mov = execMov
decodeOp Inc = execInc
decodeOp Dec = execDec
decodeOp Add = execAdd
decodeOp Sub = execSub
decodeOp Mul = execMul
decodeOp Div = execDiv
decodeOp Jmp = execJmp
decodeOp Cmp = execCmp
decodeOp Jl = execCondJmp [LT]
decodeOp Jg = execCondJmp [GT]
decodeOp Je = execCondJmp [EQ]
decodeOp Jge = execCondJmp [EQ, GT]
decodeOp Jle = execCondJmp [EQ, LT]
decodeOp Jne = execCondJmp [GT, LT]
decodeOp Call = execCall
decodeOp Ret = execRet
decodeOp Msg = execMsg
decodeOp End = execEnd


buildMachine :: String -> Maybe MachineState
buildMachine code = 
  let
    parseResult = runParser progP () "" code
  in
    case parseResult of
      Right lines ->
        let (stmts, labels) = processLabel lines
        in
          Just MachineState
            { machineRegisters = M.empty
            , machineEnd = False
            , machineLabels = labels
            , machineOutput = Nothing
            , machineProg = stmts
            , machineProgCnt = 0
            , machineCmpFlag = EQ
            , machineStack = []
            }
      _ -> Nothing


interpret :: String -> Maybe String
interpret code = do
  ms <- buildMachine code
  let (res, _) = runState (runMaybeT runMachine) ms
  res