@@ -8,6 +8,7 @@ module Development.IDE.GHC.Error
88 , diagFromString
99 , diagFromStrings
1010 , diagFromGhcException
11+ , catchSrcErrors
1112
1213 -- * utilities working with spans
1314 , srcSpanToLocation
@@ -23,6 +24,9 @@ import Development.IDE.GHC.Orphans()
2324import qualified FastString as FS
2425import GHC
2526import Bag
27+import DynFlags
28+import HscTypes
29+import Panic
2630import ErrUtils
2731import SrcLoc
2832import qualified Outputable as Out
@@ -111,6 +115,19 @@ realSpan = \case
111115 UnhelpfulSpan _ -> Nothing
112116
113117
118+-- | Run something in a Ghc monad and catch the errors (SourceErrors and
119+-- compiler-internal exceptions like Panic or InstallationError).
120+catchSrcErrors :: GhcMonad m => T.Text -> m a -> m (Either [FileDiagnostic] a)
121+catchSrcErrors fromWhere ghcM = do
122+ dflags <- getDynFlags
123+ handleGhcException (ghcExceptionToDiagnostics dflags) $
124+ handleSourceError (sourceErrorToDiagnostics dflags) $
125+ Right <$> ghcM
126+ where
127+ ghcExceptionToDiagnostics dflags = return . Left . diagFromGhcException fromWhere dflags
128+ sourceErrorToDiagnostics dflags = return . Left . diagFromErrMsgs fromWhere dflags . srcErrorMessages
129+
130+
114131diagFromGhcException :: T.Text -> DynFlags -> GhcException -> [FileDiagnostic]
115132diagFromGhcException diagSource dflags exc = diagFromString diagSource (noSpan "<Internal>") (showGHCE dflags exc)
116133