I am using GHC 9.0.2 and I am trying to compile a file like this with haskell-src-exts-1.23.1:
Main.hs
~~~~~~~
{-# LANGUAGE CPP #-}
module Main where
#define MSG "Hello world!"
main :: IO ()
main = putStrLn MSG
The basic compilation with compiler works just fine: ghc Main.hs
. But try to do the same with parseFile
:
ghci> import Language.Haskell.Exts
ghci> parseFile "Main.hs"
ParseFailed (SrcLoc "Main.hs" 5 1) "Parse error: #"
Even using parseFileWithExts [EnableExtension CPP] "Main.hs"
gives the same result.
So the question is: how to parse Haskell files with CPP macros inside of them?
CodePudding user response:
haskell-src-exts
in itself is not concerned with calling the preprocessor, so the parser fails when it sees syntax of the preprocessor (#define...
). There's a separate package that wraps a call to the preprocessor — hse-cpp
. With the Main.hs
as in the question, this works:
$ cabal install --lib haskell-src-exts hse-cpp --package-env=.
...
$ ghci
...
> import Language.Haskell.Exts
> import Language.Haskell.Exts.CPP
> parseFileWithCommentsAndCPP defaultCpphsOptions defaultParseMode "Main.hs"
ParseOk (Module ...