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