Created
February 23, 2010 09:36
-
-
Save etscrivner/312036 to your computer and use it in GitHub Desktop.
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
-- fxsk | |
-- | |
-- A simple brainfuck to c++ cross-compiler written in Haskell | |
module Main where | |
import System( getArgs ) | |
-- Define types for lexical analyzer | |
type Token = Char | |
-- Function: extractToken | |
extractToken :: Char -> [Token] | |
extractToken ch = do | |
let validTokens = ['>', '<', '+', '-', '.', ',', '[', ']'] | |
if ch `elem` validTokens | |
then [ch] | |
else [] | |
-- Function: bfLex | |
bfLex :: [Char] -> [Token] | |
bfLex (ch:xs) = (extractToken ch) ++ (bfLex xs) | |
bfLex [] = [] | |
-- Function: emitCodeFor | |
emitCodeFor :: Token -> String | |
emitCodeFor t = case t of | |
'>' -> "++ptr;" | |
'<' -> "--ptr;" | |
'+' -> "++*ptr;" | |
'-' -> "--*ptr;" | |
'.' -> "cout << *ptr;" | |
',' -> "cin >> *ptr;" | |
'[' -> "while (*ptr) {" | |
']' -> "}" | |
_ -> "*BAD TOKEN*" | |
-- Function: compile | |
compile :: [Token] -> String | |
compile (t:xs) = (emitCodeFor t) ++ (compile xs) | |
compile [] = "" | |
main = putStrLn (compile (bfLex "a++[+,]")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment