Fix Trac #2467: decent warnings for orphan instances
[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, mkWarnMsg, mkPlainErrMsg, mkLongErrMsg,
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 type Messages = (Bag WarnMsg, Bag ErrMsg)
136
137 emptyMessages :: Messages
138 emptyMessages = (emptyBag, emptyBag)
139
140 errorsFound :: DynFlags -> Messages -> Bool
141 -- The dyn-flags are used to see if the user has specified
142 -- -Werror, which says that warnings should be fatal
143 errorsFound dflags (warns, errs) 
144   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
145   | otherwise                   = not (isEmptyBag errs)
146
147 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
148 printErrorsAndWarnings dflags (warns, errs)
149   | no_errs && no_warns = return ()
150   | no_errs             = do printBagOfWarnings dflags warns
151                              when (dopt Opt_WarnIsError dflags) $
152                                  errorMsg dflags $
153                                      text "\nFailing due to -Werror.\n"
154                           -- Don't print any warnings if there are errors
155   | otherwise           = printBagOfErrors dflags errs
156   where
157     no_warns = isEmptyBag warns
158     no_errs  = isEmptyBag errs
159
160 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
161 printBagOfErrors dflags bag_of_errors
162   = sequence_   [ let style = mkErrStyle unqual
163                   in log_action dflags SevError s style (d $$ e)
164                 | ErrMsg { errMsgSpans = s:_,
165                            errMsgShortDoc = d,
166                            errMsgExtraInfo = e,
167                            errMsgContext = unqual } <- sorted_errs ]
168     where
169       bag_ls      = bagToList bag_of_errors
170       sorted_errs = sortLe occ'ed_before bag_ls
171
172       occ'ed_before err1 err2 = 
173          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
174                 LT -> True
175                 EQ -> True
176                 GT -> False
177
178 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
179 printBagOfWarnings dflags bag_of_warns
180   = sequence_   [ let style = mkErrStyle unqual
181                   in log_action dflags SevWarning s style (d $$ e)
182                 | ErrMsg { errMsgSpans = s:_,
183                            errMsgShortDoc = d,
184                            errMsgExtraInfo = e,
185                            errMsgContext = unqual } <- sorted_errs ]
186     where
187       bag_ls      = bagToList bag_of_warns
188       sorted_errs = sortLe occ'ed_before bag_ls
189
190       occ'ed_before err1 err2 = 
191          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
192                 LT -> True
193                 EQ -> True
194                 GT -> False
195
196 handleFlagWarnings :: DynFlags -> [String] -> IO ()
197 handleFlagWarnings dflags warns
198  = when (dopt Opt_WarnDeprecatedFlags dflags)
199         (handleFlagWarnings' dflags warns)
200
201 handleFlagWarnings' :: DynFlags -> [String] -> IO ()
202 handleFlagWarnings' _ [] = return ()
203 handleFlagWarnings' dflags warns
204  = do -- It would be nicer if warns :: [Message], but that has circular
205       -- import problems.
206       let warns' = map text warns
207       mapM_ (log_action dflags SevWarning noSrcSpan defaultUserStyle) warns'
208       when (dopt Opt_WarnIsError dflags) $
209           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
210              exitWith (ExitFailure 1)
211
212 ghcExit :: DynFlags -> Int -> IO ()
213 ghcExit dflags val
214   | val == 0  = exitWith ExitSuccess
215   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
216                    exitWith (ExitFailure val)
217
218 doIfSet :: Bool -> IO () -> IO ()
219 doIfSet flag action | flag      = action
220                     | otherwise = return ()
221
222 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
223 doIfSet_dyn dflags flag action | dopt flag dflags = action
224                                | otherwise        = return ()
225
226 -- -----------------------------------------------------------------------------
227 -- Dumping
228
229 dumpIfSet :: Bool -> String -> SDoc -> IO ()
230 dumpIfSet flag hdr doc
231   | not flag   = return ()
232   | otherwise  = printDump (mkDumpDoc hdr doc)
233
234 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
235 dumpIf_core cond dflags dflag hdr doc
236   | cond
237     || verbosity dflags >= 4
238     || dopt Opt_D_verbose_core2core dflags
239   = dumpSDoc dflags dflag hdr doc
240
241   | otherwise = return ()
242
243 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
244 dumpIfSet_core dflags flag hdr doc
245   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
246
247 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
248 dumpIfSet_dyn dflags flag hdr doc
249   | dopt flag dflags || verbosity dflags >= 4 
250   = dumpSDoc dflags flag hdr doc
251   | otherwise
252   = return ()
253
254 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
255 dumpIfSet_dyn_or dflags flags hdr doc
256   | or [dopt flag dflags | flag <- flags]
257   || verbosity dflags >= 4 
258   = printDump (mkDumpDoc hdr doc)
259   | otherwise = return ()
260
261 mkDumpDoc :: String -> SDoc -> SDoc
262 mkDumpDoc hdr doc 
263    = vcat [text "", 
264            line <+> text hdr <+> line,
265            doc,
266            text ""]
267      where 
268         line = text (replicate 20 '=')
269
270
271 -- | Write out a dump.
272 --      If --dump-to-file is set then this goes to a file.
273 --      otherwise emit to stdout.
274 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
275 dumpSDoc dflags dflag hdr doc
276  = do   let mFile       = chooseDumpFile dflags dflag
277         case mFile of
278                 -- write the dump to a file
279                 --      don't add the header in this case, we can see what kind
280                 --      of dump it is from the filename.
281                 Just fileName
282                  -> do  handle  <- openFile fileName AppendMode
283                         hPrintDump handle doc
284                         hClose handle
285
286                 -- write the dump to stdout
287                 Nothing
288                  -> do  printDump (mkDumpDoc hdr doc)
289
290
291 -- | Choose where to put a dump file based on DynFlags
292 --
293 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
294 chooseDumpFile dflags dflag
295
296         -- dump file location is being forced
297         --      by the --ddump-file-prefix flag.
298         | dumpToFile
299         , Just prefix   <- dumpPrefixForce dflags
300         = Just $ prefix ++ (beautifyDumpName dflag)
301
302         -- dump file location chosen by DriverPipeline.runPipeline
303         | dumpToFile
304         , Just prefix   <- dumpPrefix dflags
305         = Just $ prefix ++ (beautifyDumpName dflag)
306
307         -- we haven't got a place to put a dump file.
308         | otherwise
309         = Nothing
310
311         where   dumpToFile = dopt Opt_DumpToFile dflags
312
313
314 -- | Build a nice file name from name of a DynFlag constructor
315 beautifyDumpName :: DynFlag -> String
316 beautifyDumpName dflag
317  = let  str     = show dflag
318         cut     = if isPrefixOf "Opt_D_" str
319                          then drop 6 str
320                          else str
321         dash    = map   (\c -> case c of
322                                 '_'     -> '-'
323                                 _       -> c)
324                         cut
325    in   dash
326
327
328 -- -----------------------------------------------------------------------------
329 -- Outputting messages from the compiler
330
331 -- We want all messages to go through one place, so that we can
332 -- redirect them if necessary.  For example, when GHC is used as a
333 -- library we might want to catch all messages that GHC tries to
334 -- output and do something else with them.
335
336 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
337 ifVerbose dflags val act
338   | verbosity dflags >= val = act
339   | otherwise               = return ()
340
341 putMsg :: DynFlags -> Message -> IO ()
342 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
343
344 errorMsg :: DynFlags -> Message -> IO ()
345 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
346
347 fatalErrorMsg :: DynFlags -> Message -> IO ()
348 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
349
350 compilationProgressMsg :: DynFlags -> String -> IO ()
351 compilationProgressMsg dflags msg
352   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
353
354 showPass :: DynFlags -> String -> IO ()
355 showPass dflags what 
356   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
357
358 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
359 debugTraceMsg dflags val msg
360   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
361
362 \end{code}