ErrMsg.hs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. module ErrMsg (
  2. LogReader
  3. , setLogger
  4. , handleErrMsg
  5. ) where
  6. import Bag
  7. import Control.Applicative
  8. import Data.IORef
  9. import Data.Maybe
  10. import DynFlags
  11. import ErrUtils
  12. import GHC
  13. import qualified Gap
  14. import HscTypes
  15. import Outputable
  16. ----------------------------------------------------------------
  17. type LogReader = IO [String]
  18. ----------------------------------------------------------------
  19. setLogger :: Bool -> DynFlags -> IO (DynFlags, LogReader)
  20. setLogger False df = return (newdf, undefined)
  21. where
  22. newdf = Gap.setLogAction df $ \_ _ _ _ _ -> return ()
  23. setLogger True df = do
  24. ref <- newIORef [] :: IO (IORef [String])
  25. let newdf = Gap.setLogAction df $ appendLog ref
  26. return (newdf, reverse <$> readIORef ref)
  27. where
  28. appendLog ref _ sev src stl msg = modifyIORef ref (\ls -> ppMsg src sev msg stl : ls)
  29. ----------------------------------------------------------------
  30. handleErrMsg :: SourceError -> Ghc [String]
  31. handleErrMsg = return . errBagToStrList . srcErrorMessages
  32. errBagToStrList :: Bag ErrMsg -> [String]
  33. errBagToStrList = map ppErrMsg . reverse . bagToList
  34. ----------------------------------------------------------------
  35. ppErrMsg :: ErrMsg -> String
  36. ppErrMsg err = ppMsg spn SevError msg defaultUserStyle ++ ext
  37. where
  38. spn = head (errMsgSpans err)
  39. msg = errMsgShortDoc err
  40. ext = showMsg (errMsgExtraInfo err) defaultUserStyle
  41. ppMsg :: SrcSpan -> Severity-> SDoc -> PprStyle -> String
  42. ppMsg spn sev msg stl = fromMaybe def $ do
  43. (line,col,_,_) <- Gap.getSrcSpan spn
  44. file <- Gap.getSrcFile spn
  45. let severityCaption = Gap.showSeverityCaption sev
  46. return $ file ++ ":" ++ show line ++ ":"
  47. ++ show col ++ ":" ++ severityCaption ++ cts ++ "\0"
  48. where
  49. def = "ghc-mod:0:0:Probably mutual module import occurred\0"
  50. cts = showMsg msg stl
  51. ----------------------------------------------------------------
  52. showMsg :: SDoc -> PprStyle -> String
  53. showMsg d stl = map toNull $ Gap.renderMsg d stl
  54. where
  55. toNull '\n' = '\0'
  56. toNull x = x