Skip to content

Instantly share code, notes, and snippets.

@willtim
Created May 6, 2014 16:54
Show Gist options
  • Save willtim/083efef6ea33e507d148 to your computer and use it in GitHub Desktop.
Save willtim/083efef6ea33e507d148 to your computer and use it in GitHub Desktop.
Compiler for a stack machine
{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative
import Text.ParserCombinators.UU (pChainl)
import Text.ParserCombinators.UU.BasicInstances(pSym)
import Text.ParserCombinators.UU.Utils
-- | Huttons razor
data Exp = Add Exp Exp
| Lit Int
deriving (Show)
-- | denotational semantics
eval :: Exp -> Int
eval (Add x y) = eval x + eval y
eval (Lit i) = i
-- | Parser
pExp = foldr pChainl pAtom [Add <$ pSym '+']
where
pAtom = Lit <$> pNatural
<|> pParens pExp
parse :: String -> Exp
parse = runParser "Failed" pExp
-- | virtual stack machine
type Stack = [Int]
data Op = IAdd
| IPush Int
deriving (Show)
-- | stack vm compiler
comp :: Exp -> [Op]
comp (Add x y) = IAdd : comp x ++ comp y
comp (Lit i) = [IPush i]
-- | the vm implementation
exec :: Op -> [Int] -> [Int]
exec IAdd (x:y:os) = (x+y) : os
exec (IPush i) os = i : os
run :: Exp -> [Int]
run = foldr exec [] . comp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment