Last active
August 29, 2015 14:04
-
-
Save prakashk/0c592a37971f32e62815 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
import System.Environment (getArgs) | |
import Text.Parsec | |
import Text.Parsec.Prim | |
import Text.Parsec.Language | |
import qualified Text.Parsec.Token as T | |
import Control.Applicative ((<$>), (*>), (<*>), pure) | |
type Parser = Parsec String () | |
-- AST | |
data Program = Program [Statement] | |
deriving (Show) | |
type Location = String | |
data Statement = Print String Location | |
| Use FilePath Location | |
deriving (Show) | |
myLangDef = emptyDef { | |
T.reservedNames = [ "print", "use" ] | |
} | |
lexer = T.makeTokenParser myLangDef | |
reserved = T.reserved lexer | |
stringLiteral = T.stringLiteral lexer | |
parseString :: String -> String -> Program | |
parseString input fname = case parse program fname input of | |
Left msg -> error (show msg) | |
Right p -> p | |
parseFile :: String -> IO Program | |
parseFile fname = parseString <$> readFile fname <*> pure fname | |
-- parsers | |
program :: Parser Program | |
program = Program <$> many statement | |
statement :: Parser Statement | |
statement = printStr <|> useFile | |
printStr :: Parser Statement | |
printStr = Print <$> (reserved "print" *> stringLiteral) <*> getLocation | |
useFile :: Parser Statement | |
useFile = Use <$> (reserved "use" *> stringLiteral) <*> getLocation | |
getLocation :: Parser String | |
getLocation = do | |
pos <- getPosition | |
return $ ("(" ++ sourceName pos ++ ":" ++ (show . sourceLine) pos ++ "," ++ (show . sourceColumn) pos ++ ")") | |
-- read contents of "use"d files, parse and insert in the main AST | |
expandProgram :: Program -> IO Program | |
expandProgram (Program stmts) = Program <$> (includeUsedFiles stmts) | |
where includeUsedFiles :: [Statement] -> IO [Statement] | |
includeUsedFiles = fmap concat <$> mapM expandStatement | |
expandStatement :: Statement -> IO [Statement] | |
expandStatement stmt = | |
case stmt of | |
Use file _ -> getStatements <$> parseFile file >>= includeUsedFiles | |
_ -> return [stmt] | |
getStatements :: Program -> [Statement] | |
getStatements (Program stmts) = stmts | |
main = do | |
head <$> getArgs | |
>>= parseFile | |
>>= expandProgram | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment