Source

hpaco / hpaco-lib / Text / HPaco / Readers / Paco / Include.hs

module Text.HPaco.Readers.Paco.Include
where

import Control.Monad
import Control.Monad.IO.Class
import System.IO.Strict
import System.FilePath
import System.IO (withFile, IOMode (ReadMode))
import Text.HPaco.Readers.Paco.Basics
import Text.HPaco.Readers.Paco.ParserInternals
import Text.HPaco.Readers.Paco.Expressions
import Text.HPaco.AST.AST
import Text.HPaco.AST.Statement
import Text.HPaco.AST.Expression
import Text.HPaco.AST.Identifier

performInclude :: String -> Maybe (Identifier, Expression) -> Parser Statement
performInclude basename innerContext = do
    dirname <- psBasePath `liftM` getState
    extension <- psIncludeExtension `liftM` getState
    reader <- psHandleInclude `liftM` getState
    let fn0 = joinPath [ dirname, basename ]
    let fn = maybe fn0 (fillExtension fn0) extension
    src <- liftIO $ withFile fn ReadMode hGetContents
    subAst <- liftIO $ reader fn src
    let stmt = astRootStatement subAst
    modifyState (\s -> s { psDeps = fn:psDeps s ++ astDeps subAst })
    modifyState (\s -> s { psDefs = psDefs s ++ astDefs subAst })
    return $ maybe stmt (\(ident, expr) -> LetStatement ident expr stmt) innerContext
    where