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