Skip to content

Instantly share code, notes, and snippets.

@etscrivner
Created February 23, 2010 09:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etscrivner/312036 to your computer and use it in GitHub Desktop.
Save etscrivner/312036 to your computer and use it in GitHub Desktop.
-- 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