从 haskell 编译 haskell

Compiling haskell from haskell

所以我有一个 haskell 程序,我在其中对 haskell 源文件进行一些格式化,然后我想调用 GHC 来编译该文件,谁能告诉我该怎么做?

如果这有帮助,这是我正在制作的程序,它只是一个表情符号代码 haskell 解析器:

module EmojiParser where

import Prelude hiding (writeFile, readFile)  
import Data.Char
import Data.Text (pack, unpack)
import Path.Text.UTF8 (readFile, writeFile)
import Path.Internal

transpile filePath = do content <- readFile $ Path filePath
                        writeFile (Path filePath) . pack . parseEmoji . unpack $ content                       

parseEmoji :: [Char] -> [Char]
parseEmoji = foldl (++) "" . map f 
  where 
    minEmoji = 128511
    maxEmoji = 128592
    f x = let cval = ord x
          in if cval > minEmoji && cval < maxEmoji 
             then "emoji_symbol_" ++ (show cval) 
             else [x]

这是 ghc 用户指南中的示例: https://downloads.haskell.org/~ghc/master/users-guide/extending_ghc.html#using-ghc-as-a-library

import GHC
import GHC.Paths ( libdir )
import DynFlags ( defaultLogAction )

main =
    defaultErrorHandler defaultLogAction $ do
      runGhc (Just libdir) $ do
        dflags <- getSessionDynFlags
        setSessionDynFlags dflags
        target <- guessTarget "test_main.hs" Nothing
        setTargets [target]
        load LoadAllTargets

你应该可以做到这一点:

$ cat test_main.hs
main = putStrLn "hi"
$ ghc -package ghc simple_ghc_api.hs
[1 of 1] Compiling Main             ( simple_ghc_api.hs, simple_ghc_api.o )
Linking simple_ghc_api ...
$ ./simple_ghc_api
$ ./test_main
hi
$

一旦它像那样适合您,您应该很容易将它包含在您的程序中。