Created
May 6, 2014 16:54
-
-
Save willtim/083efef6ea33e507d148 to your computer and use it in GitHub Desktop.
Compiler for a stack machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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