{-| This library provides utilities for converting Dhall source code into a
    normalized AST
-}

module Dhall.Toml.Utils
    ( fileToDhall
    , inputToDhall
    , textToDhall
    ) where

import Data.Text    (Text)
import Data.Void    (Void)
import Dhall.Parser (Src)

import qualified Data.Text.IO    as Text.IO
import qualified Dhall.Core      as Core
import qualified Dhall.Import
import qualified Dhall.Parser
import qualified Dhall.TypeCheck

-- | Read the file fileName and return the normalized Dhall AST
fileToDhall :: String -> IO (Core.Expr Src Void)
fileToDhall :: String -> IO (Expr Src Void)
fileToDhall String
fileName = do
    Text
text <- String -> IO Text
Text.IO.readFile String
fileName
    String -> Text -> IO (Expr Src Void)
textToDhall String
fileName Text
text

-- | Read from STDIN and return the normalized Dhall AST. The file name
--   is set to "(input)"
inputToDhall :: IO (Core.Expr Src Void)
inputToDhall :: IO (Expr Src Void)
inputToDhall = do
    Text
text <- IO Text
Text.IO.getContents
    String -> Text -> IO (Expr Src Void)
textToDhall String
"(input)" Text
text

-- | Parse text and return the normalized Dhall AST. A file name is required
--   by the parser for generating error messages.
textToDhall :: String -> Text -> IO (Core.Expr Src Void)
textToDhall :: String -> Text -> IO (Expr Src Void)
textToDhall String
fileName Text
text = do
    Expr Src Import
parsedExpression <-
        Either ParseError (Expr Src Import) -> IO (Expr Src Import)
forall e (io :: * -> *) a.
(Exception e, MonadIO io) =>
Either e a -> io a
Core.throws (String -> Text -> Either ParseError (Expr Src Import)
Dhall.Parser.exprFromText String
fileName Text
text)
    Expr Src Void
resolvedExpression <- Expr Src Import -> IO (Expr Src Void)
Dhall.Import.load Expr Src Import
parsedExpression
    Expr Src Void
_ <- Either (TypeError Src Void) (Expr Src Void) -> IO (Expr Src Void)
forall e (io :: * -> *) a.
(Exception e, MonadIO io) =>
Either e a -> io a
Core.throws (Expr Src Void -> Either (TypeError Src Void) (Expr Src Void)
forall s. Expr s Void -> Either (TypeError s Void) (Expr s Void)
Dhall.TypeCheck.typeOf Expr Src Void
resolvedExpression)
    Expr Src Void -> IO (Expr Src Void)
forall (m :: * -> *) a. Monad m => a -> m a
return Expr Src Void
resolvedExpression