Add (a) CoreM monad, (b) new Annotations feature
[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     handleFlagWarnings,
18         warnIsErrorMsg,
19
20         ghcExit,
21         doIfSet, doIfSet_dyn, 
22         dumpIfSet, dumpIf_core, dumpIfSet_core, dumpIfSet_dyn, dumpIfSet_dyn_or,
23         mkDumpDoc, dumpSDoc,
24
25         --  * Messages during compilation
26         putMsg,
27         errorMsg,
28         fatalErrorMsg,
29         compilationProgressMsg,
30         showPass,
31         debugTraceMsg,  
32     ) where
33
34 #include "HsVersions.h"
35
36 import Bag              ( Bag, bagToList, isEmptyBag, emptyBag )
37 import Util             ( sortLe )
38 import Outputable
39 import SrcLoc
40 import DynFlags         ( DynFlags(..), DynFlag(..), dopt )
41 import StaticFlags      ( opt_ErrorSpans )
42
43 import Control.Monad
44 import System.Exit      ( ExitCode(..), exitWith )
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 instance Show ErrMsg where
85     show em = showSDoc (errMsgShortDoc em)
86
87 type WarnMsg = ErrMsg
88
89 -- A short (one-line) error message, with context to tell us whether
90 -- to qualify names in the message or not.
91 mkErrMsg :: SrcSpan -> PrintUnqualified -> Message -> ErrMsg
92 mkErrMsg locn print_unqual msg
93   = ErrMsg [locn] print_unqual msg empty
94
95 -- Variant that doesn't care about qualified/unqualified names
96 mkPlainErrMsg :: SrcSpan -> Message -> ErrMsg
97 mkPlainErrMsg locn msg
98   = ErrMsg [locn] alwaysQualify msg empty
99
100 -- A long (multi-line) error message, with context to tell us whether
101 -- to qualify names in the message or not.
102 mkLongErrMsg :: SrcSpan -> PrintUnqualified -> Message -> Message -> ErrMsg
103 mkLongErrMsg locn print_unqual msg extra 
104  = ErrMsg [locn] print_unqual msg extra
105
106 mkWarnMsg :: SrcSpan -> PrintUnqualified -> Message -> WarnMsg
107 mkWarnMsg = mkErrMsg
108
109 -- Variant that doesn't care about qualified/unqualified names
110 mkPlainWarnMsg :: SrcSpan -> Message -> ErrMsg
111 mkPlainWarnMsg locn msg = mkWarnMsg locn alwaysQualify msg
112
113 type Messages = (Bag WarnMsg, Bag ErrMsg)
114
115 type WarningMessages = Bag WarnMsg
116 type ErrorMessages   = Bag ErrMsg
117
118 emptyMessages :: Messages
119 emptyMessages = (emptyBag, emptyBag)
120
121 warnIsErrorMsg :: ErrMsg
122 warnIsErrorMsg = mkPlainErrMsg noSrcSpan (text "\nFailing due to -Werror.\n")
123
124 errorsFound :: DynFlags -> Messages -> Bool
125 -- The dyn-flags are used to see if the user has specified
126 -- -Werror, which says that warnings should be fatal
127 errorsFound dflags (warns, errs) 
128   | dopt Opt_WarnIsError dflags = not (isEmptyBag errs) || not (isEmptyBag warns)
129   | otherwise                   = not (isEmptyBag errs)
130
131 printErrorsAndWarnings :: DynFlags -> Messages -> IO ()
132 printErrorsAndWarnings dflags (warns, errs)
133   | no_errs && no_warns = return ()
134   | no_errs             = do printBagOfWarnings dflags warns
135                              when (dopt Opt_WarnIsError dflags) $
136                                  errorMsg dflags $
137                                      text "\nFailing due to -Werror.\n"
138                           -- Don't print any warnings if there are errors
139   | otherwise           = printBagOfErrors dflags errs
140   where
141     no_warns = isEmptyBag warns
142     no_errs  = isEmptyBag errs
143
144 printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
145 printBagOfErrors dflags bag_of_errors
146   = sequence_   [ let style = mkErrStyle unqual
147                   in log_action dflags SevError s style (d $$ e)
148                 | ErrMsg { errMsgSpans = s:_,
149                            errMsgShortDoc = d,
150                            errMsgExtraInfo = e,
151                            errMsgContext = unqual } <- sorted_errs ]
152     where
153       bag_ls      = bagToList bag_of_errors
154       sorted_errs = sortLe occ'ed_before bag_ls
155
156       occ'ed_before err1 err2 = 
157          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
158                 LT -> True
159                 EQ -> True
160                 GT -> False
161
162 printBagOfWarnings :: DynFlags -> Bag ErrMsg -> IO ()
163 printBagOfWarnings dflags bag_of_warns
164   = sequence_   [ let style = mkErrStyle unqual
165                   in log_action dflags SevWarning s style (d $$ e)
166                 | ErrMsg { errMsgSpans = s:_,
167                            errMsgShortDoc = d,
168                            errMsgExtraInfo = e,
169                            errMsgContext = unqual } <- sorted_errs ]
170     where
171       bag_ls      = bagToList bag_of_warns
172       sorted_errs = sortLe occ'ed_before bag_ls
173
174       occ'ed_before err1 err2 = 
175          case compare (head (errMsgSpans err1)) (head (errMsgSpans err2)) of
176                 LT -> True
177                 EQ -> True
178                 GT -> False
179
180 handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
181 handleFlagWarnings dflags warns
182  = when (dopt Opt_WarnDeprecatedFlags dflags)
183         (handleFlagWarnings' dflags warns)
184
185 handleFlagWarnings' :: DynFlags -> [Located String] -> IO ()
186 handleFlagWarnings' _ [] = return ()
187 handleFlagWarnings' dflags warns
188  = do -- It would be nicer if warns :: [Located Message], but that has circular
189       -- import problems.
190       mapM_ (handleFlagWarning dflags) warns
191       when (dopt Opt_WarnIsError dflags) $
192           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
193              exitWith (ExitFailure 1)
194
195 handleFlagWarning :: DynFlags -> Located String -> IO ()
196 handleFlagWarning dflags (L loc warn)
197  = log_action dflags SevWarning loc defaultUserStyle (text warn)
198
199 ghcExit :: DynFlags -> Int -> IO ()
200 ghcExit dflags val
201   | val == 0  = exitWith ExitSuccess
202   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
203                    exitWith (ExitFailure val)
204
205 doIfSet :: Bool -> IO () -> IO ()
206 doIfSet flag action | flag      = action
207                     | otherwise = return ()
208
209 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
210 doIfSet_dyn dflags flag action | dopt flag dflags = action
211                                | otherwise        = return ()
212
213 -- -----------------------------------------------------------------------------
214 -- Dumping
215
216 dumpIfSet :: Bool -> String -> SDoc -> IO ()
217 dumpIfSet flag hdr doc
218   | not flag   = return ()
219   | otherwise  = printDump (mkDumpDoc hdr doc)
220
221 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
222 dumpIf_core cond dflags dflag hdr doc
223   | cond
224     || verbosity dflags >= 4
225     || dopt Opt_D_verbose_core2core dflags
226   = dumpSDoc dflags dflag hdr doc
227
228   | otherwise = return ()
229
230 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
231 dumpIfSet_core dflags flag hdr doc
232   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
233
234 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
235 dumpIfSet_dyn dflags flag hdr doc
236   | dopt flag dflags || verbosity dflags >= 4 
237   = dumpSDoc dflags flag hdr doc
238   | otherwise
239   = return ()
240
241 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
242 dumpIfSet_dyn_or dflags flags hdr doc
243   | or [dopt flag dflags | flag <- flags]
244   || verbosity dflags >= 4 
245   = printDump (mkDumpDoc hdr doc)
246   | otherwise = return ()
247
248 mkDumpDoc :: String -> SDoc -> SDoc
249 mkDumpDoc hdr doc 
250    = vcat [text "", 
251            line <+> text hdr <+> line,
252            doc,
253            text ""]
254      where 
255         line = text (replicate 20 '=')
256
257
258 -- | Write out a dump.
259 --      If --dump-to-file is set then this goes to a file.
260 --      otherwise emit to stdout.
261 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
262 dumpSDoc dflags dflag hdr doc
263  = do   let mFile       = chooseDumpFile dflags dflag
264         case mFile of
265                 -- write the dump to a file
266                 --      don't add the header in this case, we can see what kind
267                 --      of dump it is from the filename.
268                 Just fileName
269                  -> do  handle  <- openFile fileName AppendMode
270                         hPrintDump handle doc
271                         hClose handle
272
273                 -- write the dump to stdout
274                 Nothing
275                  -> do  printDump (mkDumpDoc hdr doc)
276
277
278 -- | Choose where to put a dump file based on DynFlags
279 --
280 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
281 chooseDumpFile dflags dflag
282
283         -- dump file location is being forced
284         --      by the --ddump-file-prefix flag.
285         | dumpToFile
286         , Just prefix   <- dumpPrefixForce dflags
287         = Just $ prefix ++ (beautifyDumpName dflag)
288
289         -- dump file location chosen by DriverPipeline.runPipeline
290         | dumpToFile
291         , Just prefix   <- dumpPrefix dflags
292         = Just $ prefix ++ (beautifyDumpName dflag)
293
294         -- we haven't got a place to put a dump file.
295         | otherwise
296         = Nothing
297
298         where   dumpToFile = dopt Opt_DumpToFile dflags
299
300
301 -- | Build a nice file name from name of a DynFlag constructor
302 beautifyDumpName :: DynFlag -> String
303 beautifyDumpName dflag
304  = let  str     = show dflag
305         cut     = if isPrefixOf "Opt_D_" str
306                          then drop 6 str
307                          else str
308         dash    = map   (\c -> case c of
309                                 '_'     -> '-'
310                                 _       -> c)
311                         cut
312    in   dash
313
314
315 -- -----------------------------------------------------------------------------
316 -- Outputting messages from the compiler
317
318 -- We want all messages to go through one place, so that we can
319 -- redirect them if necessary.  For example, when GHC is used as a
320 -- library we might want to catch all messages that GHC tries to
321 -- output and do something else with them.
322
323 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
324 ifVerbose dflags val act
325   | verbosity dflags >= val = act
326   | otherwise               = return ()
327
328 putMsg :: DynFlags -> Message -> IO ()
329 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
330
331 errorMsg :: DynFlags -> Message -> IO ()
332 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
333
334 fatalErrorMsg :: DynFlags -> Message -> IO ()
335 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
336
337 compilationProgressMsg :: DynFlags -> String -> IO ()
338 compilationProgressMsg dflags msg
339   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
340
341 showPass :: DynFlags -> String -> IO ()
342 showPass dflags what 
343   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
344
345 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
346 debugTraceMsg dflags val msg
347   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
348
349 \end{code}