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