I use the GHC API to parse the module. If the module contains syntax errors, the GHC API writes them to stdout. This interferes with my program, which has a different way of reporting bugs. Session Example:
$ prog ../stack/src/Stack/Package.hs
../stack/src/Stack/Package.hs:669:0:
error: missing binary operator before token "("
#if MIN_VERSION_Cabal(1, 22, 0)
^
../stack/src/Stack/Package.hs:783:0:
error: missing binary operator before token "("
#if MIN_VERSION_Cabal(1, 22, 0)
^
../stack/src/Stack/Package.hs
error: 1:1 argon: phase `C pre-processor' failed (exitcode = 1)
Only the last should be displayed. How can I make sure the GHC API does not output anything? I would like to avoid libraries like the ones silently
that solve the problem by redirecting stdout to a temporary file.
I already tried to use it GHC.defaultErrorHandler
, but so far I can catch the exception, the GHC API is still writing to stdout. Relevant Code:
-- | Parse a module with specific instructions for the C pre-processor.
parseModuleWithCpp :: CppOptions
-> FilePath
-> IO (Either (Span, String) LModule)
parseModuleWithCpp cppOptions file =
GHC.defaultErrorHandler GHC.defaultFatalMessager (GHC.FlushOut $ return ()) $
GHC.runGhc (Just libdir) $ do
dflags <- initDynFlags file
let useCpp = GHC.xopt GHC.Opt_Cpp dflags
fileContents <-
if useCpp
then getPreprocessedSrcDirect cppOptions file
else GHC.liftIO $ readFile file
return $
case parseFile dflags file fileContents of
GHC.PFailed ss m -> Left (srcSpanToSpan ss, GHC.showSDoc dflags m)
GHC.POk _ pmod -> Right pmod
Also, with this approach, I cannot catch the error message (I just get it ExitFailure
). Deleting a line using GHC.defaultErrorHandler
gives me the result shown above.