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