on d82d607 help sign in
ormolu/src/Ormolu/Exception.hs
74 lines 2.3 kB history raw
1{-# LANGUAGE LambdaCase #-}
3-- | 'OrmoluException' type and surrounding definitions.
5module Ormolu.Exception
6 ( OrmoluException (..)
7 , withPrettyOrmoluExceptions
8 )
9where
11import Control.Exception
12import Data.Text (Text)
13import Ormolu.Utils (showOutputable)
14import System.Exit (ExitCode (..), exitWith)
15import System.IO
16import qualified GHC
18-- | Ormolu exception representing all cases when Ormolu can fail.
20data OrmoluException
21 = OrmoluCppEnabled
22 -- ^ Ormolu does not work with source files that use CPP
23 | OrmoluParsingFailed GHC.SrcSpan String
24 -- ^ Parsing of original source code failed
25 | OrmoluOutputParsingFailed GHC.SrcSpan String
26 -- ^ Parsing of formatted source code failed
27 | OrmoluASTDiffers String Text
28 -- ^ Original and resulting ASTs differ, first argument is the original
29 -- source code, second argument is rendered source code
30 deriving (Eq, Show)
32instance Exception OrmoluException where
33 displayException = \case
34 OrmoluCppEnabled -> "CPP is not supported"
35 OrmoluParsingFailed s e ->
36 showParsingErr "Parsing of source code failed:" s e
37 OrmoluOutputParsingFailed s e ->
38 showParsingErr "Parsing of formatted code failed:" s e ++
39 "Please, consider reporting the bug."
40 OrmoluASTDiffers _ _ -> unlines
41 [ "AST of input and AST of formatted code differ."
42 , "Please, consider reporting the bug."
43 ]
45-- | Inside this wrapper 'OrmoluException' will be caught and displayed
46-- nicely using 'displayException'.
48withPrettyOrmoluExceptions
49 :: IO a -- ^ Action that may throw the exception
50 -> IO a
51withPrettyOrmoluExceptions m = m `catch` h
52 where
53 h :: OrmoluException -> IO a
54 h e = do
55 hPutStrLn stderr (displayException e)
56 exitWith . ExitFailure $
57 case e of
58 -- Error code 1 is for `error` or `notImplemented`
59 OrmoluCppEnabled -> 2
60 OrmoluParsingFailed _ _ -> 3
61 OrmoluOutputParsingFailed _ _ -> 4
62 OrmoluASTDiffers _ _ -> 5
64----------------------------------------------------------------------------
65-- Helpers
67-- | Show a parse error.
69showParsingErr :: String -> GHC.SrcSpan -> String -> String
70showParsingErr msg spn err = unlines
71 [ msg
72 , showOutputable spn
73 , err
74 ]