Give the "Failing due to -Werror" message a name.
[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 #if __GLASGOW_HASKELL__ >= 609
87 instance Exception ErrMsg
88 #endif
89
90 instance Show ErrMsg where
91     show em = showSDoc (errMsgShortDoc em)
92
93 throwErrMsg :: ErrMsg -> a
94 #if __GLASGOW_HASKELL__ < 609
95 throwErrMsg = throwDyn
96 #else
97 throwErrMsg = throw
98 #endif
99
100 handleErrMsg :: (ErrMsg -> IO a) -> IO a -> IO a
101 #if __GLASGOW_HASKELL__ < 609
102 handleErrMsg = flip catchDyn
103 #else
104 handleErrMsg = handle
105 #endif
106
107 -- So we can throw these things as exceptions
108 errMsgTc :: TyCon
109 errMsgTc = mkTyCon "ErrMsg"
110 {-# NOINLINE errMsgTc #-}
111 instance Typeable ErrMsg where
112   typeOf _ = mkTyConApp errMsgTc []
113
114 type WarnMsg = ErrMsg
115
116 -- A short (one-line) error message, with context to tell us whether
117 -- to qualify names in the message or not.
118 mkErrMsg :: SrcSpan -> PrintUnqualified -> Message -> ErrMsg
119 mkErrMsg locn print_unqual msg
120   = ErrMsg [locn] print_unqual msg empty
121
122 -- Variant that doesn't care about qualified/unqualified names
123 mkPlainErrMsg :: SrcSpan -> Message -> ErrMsg
124 mkPlainErrMsg locn msg
125   = ErrMsg [locn] alwaysQualify msg empty
126
127 -- A long (multi-line) error message, with context to tell us whether
128 -- to qualify names in the message or not.
129 mkLongErrMsg :: SrcSpan -> PrintUnqualified -> Message -> Message -> ErrMsg
130 mkLongErrMsg locn print_unqual msg extra 
131  = ErrMsg [locn] print_unqual msg extra
132
133 mkWarnMsg :: SrcSpan -> PrintUnqualified -> Message -> WarnMsg
134 mkWarnMsg = mkErrMsg
135
136 -- Variant that doesn't care about qualified/unqualified names
137 mkPlainWarnMsg :: SrcSpan -> Message -> ErrMsg
138 mkPlainWarnMsg locn msg = mkWarnMsg locn alwaysQualify msg
139
140 type Messages = (Bag WarnMsg, Bag ErrMsg)
141
142 type WarningMessages = Bag WarnMsg
143 type ErrorMessages   = Bag ErrMsg
144
145 emptyMessages :: Messages
146 emptyMessages = (emptyBag, emptyBag)
147
148 warnIsErrorMsg :: ErrMsg
149 warnIsErrorMsg = mkPlainErrMsg noSrcSpan (text "\nFailing due to -Werror.\n")
150
151 errorsFound :: DynFlags -> Messages -> Bool
152 -- The dyn-flags are used to see if the user has specified
153 -- -Werror, which says that warnings should be fatal
154 errorsFound dflags (warns, errs) 
155   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
156   | otherwise                   = not (isEmptyBag errs)
157
158 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
159 printErrorsAndWarnings dflags (warns, errs)
160   | no_errs && no_warns = return ()
161   | no_errs             = do printBagOfWarnings dflags warns
162                              when (dopt Opt_WarnIsError dflags) $
163                                  errorMsg dflags $
164                                      text "\nFailing due to -Werror.\n"
165                           -- Don't print any warnings if there are errors
166   | otherwise           = printBagOfErrors dflags errs
167   where
168     no_warns = isEmptyBag warns
169     no_errs  = isEmptyBag errs
170
171 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
172 printBagOfErrors dflags bag_of_errors
173   = sequence_   [ let style = mkErrStyle unqual
174                   in log_action dflags SevError s style (d $$ e)
175                 | ErrMsg { errMsgSpans = s:_,
176                            errMsgShortDoc = d,
177                            errMsgExtraInfo = e,
178                            errMsgContext = unqual } <- sorted_errs ]
179     where
180       bag_ls      = bagToList bag_of_errors
181       sorted_errs = sortLe occ'ed_before bag_ls
182
183       occ'ed_before err1 err2 = 
184          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
185                 LT -> True
186                 EQ -> True
187                 GT -> False
188
189 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
190 printBagOfWarnings dflags bag_of_warns
191   = sequence_   [ let style = mkErrStyle unqual
192                   in log_action dflags SevWarning s style (d $$ e)
193                 | ErrMsg { errMsgSpans = s:_,
194                            errMsgShortDoc = d,
195                            errMsgExtraInfo = e,
196                            errMsgContext = unqual } <- sorted_errs ]
197     where
198       bag_ls      = bagToList bag_of_warns
199       sorted_errs = sortLe occ'ed_before bag_ls
200
201       occ'ed_before err1 err2 = 
202          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
203                 LT -> True
204                 EQ -> True
205                 GT -> False
206
207 handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
208 handleFlagWarnings dflags warns
209  = when (dopt Opt_WarnDeprecatedFlags dflags)
210         (handleFlagWarnings' dflags warns)
211
212 handleFlagWarnings' :: DynFlags -> [Located String] -> IO ()
213 handleFlagWarnings' _ [] = return ()
214 handleFlagWarnings' dflags warns
215  = do -- It would be nicer if warns :: [Located Message], but that has circular
216       -- import problems.
217       mapM_ (handleFlagWarning dflags) warns
218       when (dopt Opt_WarnIsError dflags) $
219           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
220              exitWith (ExitFailure 1)
221
222 handleFlagWarning :: DynFlags -> Located String -> IO ()
223 handleFlagWarning dflags (L loc warn)
224  = log_action dflags SevWarning loc defaultUserStyle (text warn)
225
226 ghcExit :: DynFlags -> Int -> IO ()
227 ghcExit dflags val
228   | val == 0  = exitWith ExitSuccess
229   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
230                    exitWith (ExitFailure val)
231
232 doIfSet :: Bool -> IO () -> IO ()
233 doIfSet flag action | flag      = action
234                     | otherwise = return ()
235
236 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
237 doIfSet_dyn dflags flag action | dopt flag dflags = action
238                                | otherwise        = return ()
239
240 -- -----------------------------------------------------------------------------
241 -- Dumping
242
243 dumpIfSet :: Bool -> String -> SDoc -> IO ()
244 dumpIfSet flag hdr doc
245   | not flag   = return ()
246   | otherwise  = printDump (mkDumpDoc hdr doc)
247
248 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
249 dumpIf_core cond dflags dflag hdr doc
250   | cond
251     || verbosity dflags >= 4
252     || dopt Opt_D_verbose_core2core dflags
253   = dumpSDoc dflags dflag hdr doc
254
255   | otherwise = return ()
256
257 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
258 dumpIfSet_core dflags flag hdr doc
259   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
260
261 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
262 dumpIfSet_dyn dflags flag hdr doc
263   | dopt flag dflags || verbosity dflags >= 4 
264   = dumpSDoc dflags flag hdr doc
265   | otherwise
266   = return ()
267
268 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
269 dumpIfSet_dyn_or dflags flags hdr doc
270   | or [dopt flag dflags | flag <- flags]
271   || verbosity dflags >= 4 
272   = printDump (mkDumpDoc hdr doc)
273   | otherwise = return ()
274
275 mkDumpDoc :: String -> SDoc -> SDoc
276 mkDumpDoc hdr doc 
277    = vcat [text "", 
278            line <+> text hdr <+> line,
279            doc,
280            text ""]
281      where 
282         line = text (replicate 20 '=')
283
284
285 -- | Write out a dump.
286 --      If --dump-to-file is set then this goes to a file.
287 --      otherwise emit to stdout.
288 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
289 dumpSDoc dflags dflag hdr doc
290  = do   let mFile       = chooseDumpFile dflags dflag
291         case mFile of
292                 -- write the dump to a file
293                 --      don't add the header in this case, we can see what kind
294                 --      of dump it is from the filename.
295                 Just fileName
296                  -> do  handle  <- openFile fileName AppendMode
297                         hPrintDump handle doc
298                         hClose handle
299
300                 -- write the dump to stdout
301                 Nothing
302                  -> do  printDump (mkDumpDoc hdr doc)
303
304
305 -- | Choose where to put a dump file based on DynFlags
306 --
307 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
308 chooseDumpFile dflags dflag
309
310         -- dump file location is being forced
311         --      by the --ddump-file-prefix flag.
312         | dumpToFile
313         , Just prefix   <- dumpPrefixForce dflags
314         = Just $ prefix ++ (beautifyDumpName dflag)
315
316         -- dump file location chosen by DriverPipeline.runPipeline
317         | dumpToFile
318         , Just prefix   <- dumpPrefix dflags
319         = Just $ prefix ++ (beautifyDumpName dflag)
320
321         -- we haven't got a place to put a dump file.
322         | otherwise
323         = Nothing
324
325         where   dumpToFile = dopt Opt_DumpToFile dflags
326
327
328 -- | Build a nice file name from name of a DynFlag constructor
329 beautifyDumpName :: DynFlag -> String
330 beautifyDumpName dflag
331  = let  str     = show dflag
332         cut     = if isPrefixOf "Opt_D_" str
333                          then drop 6 str
334                          else str
335         dash    = map   (\c -> case c of
336                                 '_'     -> '-'
337                                 _       -> c)
338                         cut
339    in   dash
340
341
342 -- -----------------------------------------------------------------------------
343 -- Outputting messages from the compiler
344
345 -- We want all messages to go through one place, so that we can
346 -- redirect them if necessary.  For example, when GHC is used as a
347 -- library we might want to catch all messages that GHC tries to
348 -- output and do something else with them.
349
350 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
351 ifVerbose dflags val act
352   | verbosity dflags >= val = act
353   | otherwise               = return ()
354
355 putMsg :: DynFlags -> Message -> IO ()
356 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
357
358 errorMsg :: DynFlags -> Message -> IO ()
359 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
360
361 fatalErrorMsg :: DynFlags -> Message -> IO ()
362 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
363
364 compilationProgressMsg :: DynFlags -> String -> IO ()
365 compilationProgressMsg dflags msg
366   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
367
368 showPass :: DynFlags -> String -> IO ()
369 showPass dflags what 
370   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
371
372 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
373 debugTraceMsg dflags val msg
374   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
375
376 \end{code}