Use an extensible-exceptions package when bootstrapping
[ghc-hetmet.git] / compiler / main / ErrUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[ErrsUtils]{Utilities for error reporting}
5
6 \begin{code}
7 module ErrUtils (
8         Message, mkLocMessage, printError,
9         Severity(..),
10
11         ErrMsg, WarnMsg, throwErrMsg, handleErrMsg,
12     ErrorMessages, WarningMessages,
13         errMsgSpans, errMsgContext, errMsgShortDoc, errMsgExtraInfo,
14         Messages, errorsFound, emptyMessages,
15         mkErrMsg, mkPlainErrMsg, mkLongErrMsg, mkWarnMsg, mkPlainWarnMsg,
16         printErrorsAndWarnings, printBagOfErrors, printBagOfWarnings,
17     handleFlagWarnings,
18         warnIsErrorMsg,
19
20         ghcExit,
21         doIfSet, doIfSet_dyn, 
22         dumpIfSet, dumpIf_core, dumpIfSet_core, dumpIfSet_dyn, dumpIfSet_dyn_or,
23         mkDumpDoc, dumpSDoc,
24
25         --  * Messages during compilation
26         putMsg,
27         errorMsg,
28         fatalErrorMsg,
29         compilationProgressMsg,
30         showPass,
31         debugTraceMsg,  
32     ) where
33
34 #include "HsVersions.h"
35
36 import Bag              ( Bag, bagToList, isEmptyBag, emptyBag )
37 import Util             ( sortLe )
38 import Outputable
39 import SrcLoc
40 import DynFlags         ( DynFlags(..), DynFlag(..), dopt )
41 import StaticFlags      ( opt_ErrorSpans )
42
43 import Control.Monad
44 import System.Exit      ( ExitCode(..), exitWith )
45 import Data.Dynamic
46 import Data.List
47 import System.IO
48 import Exception
49
50 -- -----------------------------------------------------------------------------
51 -- Basic error messages: just render a message with a source location.
52
53 type Message = SDoc
54
55 data Severity
56   = SevInfo
57   | SevWarning
58   | SevError
59   | SevFatal
60
61 mkLocMessage :: SrcSpan -> Message -> Message
62 mkLocMessage locn msg
63   | opt_ErrorSpans = hang (ppr locn <> colon) 4 msg
64   | otherwise      = hang (ppr (srcSpanStart locn) <> colon) 4 msg
65   -- always print the location, even if it is unhelpful.  Error messages
66   -- are supposed to be in a standard format, and one without a location
67   -- would look strange.  Better to say explicitly "<no location info>".
68
69 printError :: SrcSpan -> Message -> IO ()
70 printError span msg = printErrs (mkLocMessage span msg $ defaultErrStyle)
71
72
73 -- -----------------------------------------------------------------------------
74 -- Collecting up messages for later ordering and printing.
75
76 data ErrMsg = ErrMsg { 
77         errMsgSpans     :: [SrcSpan],
78         errMsgContext   :: PrintUnqualified,
79         errMsgShortDoc  :: Message,
80         errMsgExtraInfo :: Message
81         }
82         -- The SrcSpan is used for sorting errors into line-number order
83         -- NB  Pretty.Doc not SDoc: we deal with the printing style (in ptic 
84         -- whether to qualify an External Name) at the error occurrence
85
86 instance Exception ErrMsg
87
88 instance Show ErrMsg where
89     show em = showSDoc (errMsgShortDoc em)
90
91 throwErrMsg :: ErrMsg -> a
92 throwErrMsg = throw
93
94 handleErrMsg :: ExceptionMonad m => (ErrMsg -> m a) -> m a -> m a
95 handleErrMsg = ghandle
96
97 -- So we can throw these things as exceptions
98 errMsgTc :: TyCon
99 errMsgTc = mkTyCon "ErrMsg"
100 {-# NOINLINE errMsgTc #-}
101 instance Typeable ErrMsg where
102   typeOf _ = mkTyConApp errMsgTc []
103
104 type WarnMsg = ErrMsg
105
106 -- A short (one-line) error message, with context to tell us whether
107 -- to qualify names in the message or not.
108 mkErrMsg :: SrcSpan -> PrintUnqualified -> Message -> ErrMsg
109 mkErrMsg locn print_unqual msg
110   = ErrMsg [locn] print_unqual msg empty
111
112 -- Variant that doesn't care about qualified/unqualified names
113 mkPlainErrMsg :: SrcSpan -> Message -> ErrMsg
114 mkPlainErrMsg locn msg
115   = ErrMsg [locn] alwaysQualify msg empty
116
117 -- A long (multi-line) error message, with context to tell us whether
118 -- to qualify names in the message or not.
119 mkLongErrMsg :: SrcSpan -> PrintUnqualified -> Message -> Message -> ErrMsg
120 mkLongErrMsg locn print_unqual msg extra 
121  = ErrMsg [locn] print_unqual msg extra
122
123 mkWarnMsg :: SrcSpan -> PrintUnqualified -> Message -> WarnMsg
124 mkWarnMsg = mkErrMsg
125
126 -- Variant that doesn't care about qualified/unqualified names
127 mkPlainWarnMsg :: SrcSpan -> Message -> ErrMsg
128 mkPlainWarnMsg locn msg = mkWarnMsg locn alwaysQualify msg
129
130 type Messages = (Bag WarnMsg, Bag ErrMsg)
131
132 type WarningMessages = Bag WarnMsg
133 type ErrorMessages   = Bag ErrMsg
134
135 emptyMessages :: Messages
136 emptyMessages = (emptyBag, emptyBag)
137
138 warnIsErrorMsg :: ErrMsg
139 warnIsErrorMsg = mkPlainErrMsg noSrcSpan (text "\nFailing due to -Werror.\n")
140
141 errorsFound :: DynFlags -> Messages -> Bool
142 -- The dyn-flags are used to see if the user has specified
143 -- -Werror, which says that warnings should be fatal
144 errorsFound dflags (warns, errs) 
145   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
146   | otherwise                   = not (isEmptyBag errs)
147
148 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
149 printErrorsAndWarnings dflags (warns, errs)
150   | no_errs && no_warns = return ()
151   | no_errs             = do printBagOfWarnings dflags warns
152                              when (dopt Opt_WarnIsError dflags) $
153                                  errorMsg dflags $
154                                      text "\nFailing due to -Werror.\n"
155                           -- Don't print any warnings if there are errors
156   | otherwise           = printBagOfErrors dflags errs
157   where
158     no_warns = isEmptyBag warns
159     no_errs  = isEmptyBag errs
160
161 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
162 printBagOfErrors dflags bag_of_errors
163   = sequence_   [ let style = mkErrStyle unqual
164                   in log_action dflags SevError s style (d $$ e)
165                 | ErrMsg { errMsgSpans = s:_,
166                            errMsgShortDoc = d,
167                            errMsgExtraInfo = e,
168                            errMsgContext = unqual } <- sorted_errs ]
169     where
170       bag_ls      = bagToList bag_of_errors
171       sorted_errs = sortLe occ'ed_before bag_ls
172
173       occ'ed_before err1 err2 = 
174          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
175                 LT -> True
176                 EQ -> True
177                 GT -> False
178
179 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
180 printBagOfWarnings dflags bag_of_warns
181   = sequence_   [ let style = mkErrStyle unqual
182                   in log_action dflags SevWarning s style (d $$ e)
183                 | ErrMsg { errMsgSpans = s:_,
184                            errMsgShortDoc = d,
185                            errMsgExtraInfo = e,
186                            errMsgContext = unqual } <- sorted_errs ]
187     where
188       bag_ls      = bagToList bag_of_warns
189       sorted_errs = sortLe occ'ed_before bag_ls
190
191       occ'ed_before err1 err2 = 
192          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
193                 LT -> True
194                 EQ -> True
195                 GT -> False
196
197 handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
198 handleFlagWarnings dflags warns
199  = when (dopt Opt_WarnDeprecatedFlags dflags)
200         (handleFlagWarnings' dflags warns)
201
202 handleFlagWarnings' :: DynFlags -> [Located String] -> IO ()
203 handleFlagWarnings' _ [] = return ()
204 handleFlagWarnings' dflags warns
205  = do -- It would be nicer if warns :: [Located Message], but that has circular
206       -- import problems.
207       mapM_ (handleFlagWarning dflags) warns
208       when (dopt Opt_WarnIsError dflags) $
209           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
210              exitWith (ExitFailure 1)
211
212 handleFlagWarning :: DynFlags -> Located String -> IO ()
213 handleFlagWarning dflags (L loc warn)
214  = log_action dflags SevWarning loc defaultUserStyle (text warn)
215
216 ghcExit :: DynFlags -> Int -> IO ()
217 ghcExit dflags val
218   | val == 0  = exitWith ExitSuccess
219   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
220                    exitWith (ExitFailure val)
221
222 doIfSet :: Bool -> IO () -> IO ()
223 doIfSet flag action | flag      = action
224                     | otherwise = return ()
225
226 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
227 doIfSet_dyn dflags flag action | dopt flag dflags = action
228                                | otherwise        = return ()
229
230 -- -----------------------------------------------------------------------------
231 -- Dumping
232
233 dumpIfSet :: Bool -> String -> SDoc -> IO ()
234 dumpIfSet flag hdr doc
235   | not flag   = return ()
236   | otherwise  = printDump (mkDumpDoc hdr doc)
237
238 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
239 dumpIf_core cond dflags dflag hdr doc
240   | cond
241     || verbosity dflags >= 4
242     || dopt Opt_D_verbose_core2core dflags
243   = dumpSDoc dflags dflag hdr doc
244
245   | otherwise = return ()
246
247 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
248 dumpIfSet_core dflags flag hdr doc
249   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
250
251 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
252 dumpIfSet_dyn dflags flag hdr doc
253   | dopt flag dflags || verbosity dflags >= 4 
254   = dumpSDoc dflags flag hdr doc
255   | otherwise
256   = return ()
257
258 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
259 dumpIfSet_dyn_or dflags flags hdr doc
260   | or [dopt flag dflags | flag <- flags]
261   || verbosity dflags >= 4 
262   = printDump (mkDumpDoc hdr doc)
263   | otherwise = return ()
264
265 mkDumpDoc :: String -> SDoc -> SDoc
266 mkDumpDoc hdr doc 
267    = vcat [text "", 
268            line <+> text hdr <+> line,
269            doc,
270            text ""]
271      where 
272         line = text (replicate 20 '=')
273
274
275 -- | Write out a dump.
276 --      If --dump-to-file is set then this goes to a file.
277 --      otherwise emit to stdout.
278 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
279 dumpSDoc dflags dflag hdr doc
280  = do   let mFile       = chooseDumpFile dflags dflag
281         case mFile of
282                 -- write the dump to a file
283                 --      don't add the header in this case, we can see what kind
284                 --      of dump it is from the filename.
285                 Just fileName
286                  -> do  handle  <- openFile fileName AppendMode
287                         hPrintDump handle doc
288                         hClose handle
289
290                 -- write the dump to stdout
291                 Nothing
292                  -> do  printDump (mkDumpDoc hdr doc)
293
294
295 -- | Choose where to put a dump file based on DynFlags
296 --
297 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
298 chooseDumpFile dflags dflag
299
300         -- dump file location is being forced
301         --      by the --ddump-file-prefix flag.
302         | dumpToFile
303         , Just prefix   <- dumpPrefixForce dflags
304         = Just $ prefix ++ (beautifyDumpName dflag)
305
306         -- dump file location chosen by DriverPipeline.runPipeline
307         | dumpToFile
308         , Just prefix   <- dumpPrefix dflags
309         = Just $ prefix ++ (beautifyDumpName dflag)
310
311         -- we haven't got a place to put a dump file.
312         | otherwise
313         = Nothing
314
315         where   dumpToFile = dopt Opt_DumpToFile dflags
316
317
318 -- | Build a nice file name from name of a DynFlag constructor
319 beautifyDumpName :: DynFlag -> String
320 beautifyDumpName dflag
321  = let  str     = show dflag
322         cut     = if isPrefixOf "Opt_D_" str
323                          then drop 6 str
324                          else str
325         dash    = map   (\c -> case c of
326                                 '_'     -> '-'
327                                 _       -> c)
328                         cut
329    in   dash
330
331
332 -- -----------------------------------------------------------------------------
333 -- Outputting messages from the compiler
334
335 -- We want all messages to go through one place, so that we can
336 -- redirect them if necessary.  For example, when GHC is used as a
337 -- library we might want to catch all messages that GHC tries to
338 -- output and do something else with them.
339
340 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
341 ifVerbose dflags val act
342   | verbosity dflags >= val = act
343   | otherwise               = return ()
344
345 putMsg :: DynFlags -> Message -> IO ()
346 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
347
348 errorMsg :: DynFlags -> Message -> IO ()
349 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
350
351 fatalErrorMsg :: DynFlags -> Message -> IO ()
352 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
353
354 compilationProgressMsg :: DynFlags -> String -> IO ()
355 compilationProgressMsg dflags msg
356   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
357
358 showPass :: DynFlags -> String -> IO ()
359 showPass dflags what 
360   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
361
362 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
363 debugTraceMsg dflags val msg
364   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
365
366 \end{code}