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