Expand ErrUtils api with another plain variant
[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         errMsgSpans, errMsgContext, errMsgShortDoc, errMsgExtraInfo,
13         Messages, errorsFound, emptyMessages,
14         mkErrMsg, mkPlainErrMsg, mkLongErrMsg, mkWarnMsg, mkPlainWarnMsg,
15         printErrorsAndWarnings, printBagOfErrors, printBagOfWarnings,
16     handleFlagWarnings,
17
18         ghcExit,
19         doIfSet, doIfSet_dyn, 
20         dumpIfSet, dumpIf_core, dumpIfSet_core, dumpIfSet_dyn, dumpIfSet_dyn_or,
21         mkDumpDoc, dumpSDoc,
22
23         --  * Messages during compilation
24         putMsg,
25         errorMsg,
26         fatalErrorMsg,
27         compilationProgressMsg,
28         showPass,
29         debugTraceMsg,  
30     ) where
31
32 #include "HsVersions.h"
33
34 import Bag              ( Bag, bagToList, isEmptyBag, emptyBag )
35 import SrcLoc           ( SrcSpan )
36 import Util             ( sortLe )
37 import Outputable
38 import SrcLoc           ( srcSpanStart, noSrcSpan )
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 emptyMessages :: Messages
142 emptyMessages = (emptyBag, emptyBag)
143
144 errorsFound :: DynFlags -> Messages -> Bool
145 -- The dyn-flags are used to see if the user has specified
146 -- -Werror, which says that warnings should be fatal
147 errorsFound dflags (warns, errs) 
148   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
149   | otherwise                   = not (isEmptyBag errs)
150
151 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
152 printErrorsAndWarnings dflags (warns, errs)
153   | no_errs && no_warns = return ()
154   | no_errs             = do printBagOfWarnings dflags warns
155                              when (dopt Opt_WarnIsError dflags) $
156                                  errorMsg dflags $
157                                      text "\nFailing due to -Werror.\n"
158                           -- Don't print any warnings if there are errors
159   | otherwise           = printBagOfErrors dflags errs
160   where
161     no_warns = isEmptyBag warns
162     no_errs  = isEmptyBag errs
163
164 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
165 printBagOfErrors dflags bag_of_errors
166   = sequence_   [ let style = mkErrStyle unqual
167                   in log_action dflags SevError s style (d $$ e)
168                 | ErrMsg { errMsgSpans = s:_,
169                            errMsgShortDoc = d,
170                            errMsgExtraInfo = e,
171                            errMsgContext = unqual } <- sorted_errs ]
172     where
173       bag_ls      = bagToList bag_of_errors
174       sorted_errs = sortLe occ'ed_before bag_ls
175
176       occ'ed_before err1 err2 = 
177          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
178                 LT -> True
179                 EQ -> True
180                 GT -> False
181
182 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
183 printBagOfWarnings dflags bag_of_warns
184   = sequence_   [ let style = mkErrStyle unqual
185                   in log_action dflags SevWarning s style (d $$ e)
186                 | ErrMsg { errMsgSpans = s:_,
187                            errMsgShortDoc = d,
188                            errMsgExtraInfo = e,
189                            errMsgContext = unqual } <- sorted_errs ]
190     where
191       bag_ls      = bagToList bag_of_warns
192       sorted_errs = sortLe occ'ed_before bag_ls
193
194       occ'ed_before err1 err2 = 
195          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
196                 LT -> True
197                 EQ -> True
198                 GT -> False
199
200 handleFlagWarnings :: DynFlags -> [String] -> IO ()
201 handleFlagWarnings dflags warns
202  = when (dopt Opt_WarnDeprecatedFlags dflags)
203         (handleFlagWarnings' dflags warns)
204
205 handleFlagWarnings' :: DynFlags -> [String] -> IO ()
206 handleFlagWarnings' _ [] = return ()
207 handleFlagWarnings' dflags warns
208  = do -- It would be nicer if warns :: [Message], but that has circular
209       -- import problems.
210       let warns' = map text warns
211       mapM_ (log_action dflags SevWarning noSrcSpan defaultUserStyle) warns'
212       when (dopt Opt_WarnIsError dflags) $
213           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
214              exitWith (ExitFailure 1)
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}