Last active
August 29, 2015 14:04
-
-
Save prakashk/2d0fb2e836a8351f599d 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, liftA2) | |
type Parser = Parsec String () | |
type Location = String | |
type LocNode a = (Location, a) | |
-- AST | |
data Program = Program [LocNode Statement] | |
deriving (Show) | |
data Statement = Print String | |
| Use FilePath | |
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 fname = | |
either (error . show) id . | |
parse program fname | |
parseFile :: String -> IO Program | |
parseFile fname = parseString <$> readFile fname <*> pure fname | |
-- parsers | |
program :: Parser Program | |
program = Program <$> many statement | |
statement :: Parser (LocNode Statement) | |
statement = printStr <|> useFile | |
printStr :: Parser (LocNode Statement) | |
printStr = withLocation $ Print <$> (reserved "print" *> stringLiteral) | |
useFile :: Parser (LocNode Statement) | |
useFile = withLocation $ Use <$> (reserved "use" *> stringLiteral) | |
withLocation :: Parser a -> Parser (LocNode a) | |
withLocation = liftA2 (,) 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 :: [LocNode Statement] -> IO [LocNode Statement] | |
includeUsedFiles = fmap concat <$> mapM expandStatement | |
expandStatement :: LocNode Statement -> IO [LocNode Statement] | |
expandStatement (loc, stmt) = | |
case stmt of | |
Use file -> getStatements <$> parseFile file >>= includeUsedFiles | |
_ -> return [(loc, stmt)] | |
getStatements :: Program -> [LocNode 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