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