summaryrefslogtreecommitdiffstats
path: root/src/main.hs
blob: 90de59e4ed1ad70bac45d1b9649605cbd0e8e8c7 (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
module Main where

import Data.Char
import System.Environment (getArgs)
import Utils

getFilename [] = error "empty argument list"
getFilename (f : fs) = f

data LWord
  = LSymbol String
  | LInteger Integer
  deriving (Show)

reprWord (LSymbol a) = a
reprWord (LInteger a) = show a

parseWord rawStr
  | all isDigit rawStr = LInteger (read rawStr)
  | otherwise = LSymbol rawStr

parseSource source = source $> words .> map parseWord

interpretSource :: [LWord] -> [LWord] -> IO ()
interpretSource _ [] = putStrLn "done"
interpretSource stack (word : rest) = do
  newStack <- interpretWord stack word
  interpretSource newStack rest

interpretWord :: [LWord] -> LWord -> IO [LWord]
interpretWord stack word@(LInteger value) = pure $ word : stack
interpretWord (a : stack) word@(LSymbol ".") = do
  putStrLn $ reprWord a
  pure stack
interpretWord ((LInteger a) : (LInteger b) : stack) word@(LSymbol "+") = pure $ LInteger (a + b) : stack
interpretWord _ other = error $ "[error] runtime error at " ++ show other

main :: IO ()
main = do
  args <- getArgs
  let filename = getFilename args
  putStrLn $ "[info] executing file " ++ filename
  source <- readFile filename
  putStrLn source
  let parsed = parseSource source
  putStrLn $ "[info] parsed words:\n" ++ show parsed
  putStrLn "[info] interpreter output:"
  interpretSource [] parsed