Allow flags to be marked as deprecated
[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 _ [] = return ()
180 handleFlagWarnings dflags warns
181  = do -- It would be nicer if warns :: [Message], but that has circular
182       -- import problems.
183       let warns' = map text warns
184       mapM_ (log_action dflags SevWarning noSrcSpan defaultUserStyle) warns'
185       when (dopt Opt_WarnIsError dflags) $
186           do errorMsg dflags $ text "\nFailing due to -Werror.\n"
187              exitWith (ExitFailure 1)
188
189 ghcExit :: DynFlags -> Int -> IO ()
190 ghcExit dflags val
191   | val == 0  = exitWith ExitSuccess
192   | otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
193                    exitWith (ExitFailure val)
194
195 doIfSet :: Bool -> IO () -> IO ()
196 doIfSet flag action | flag      = action
197                     | otherwise = return ()
198
199 doIfSet_dyn :: DynFlags -> DynFlag -> IO () -> IO()
200 doIfSet_dyn dflags flag action | dopt flag dflags = action
201                                | otherwise        = return ()
202
203 -- -----------------------------------------------------------------------------
204 -- Dumping
205
206 dumpIfSet :: Bool -> String -> SDoc -> IO ()
207 dumpIfSet flag hdr doc
208   | not flag   = return ()
209   | otherwise  = printDump (mkDumpDoc hdr doc)
210
211 dumpIf_core :: Bool -> DynFlags -> DynFlag -> String -> SDoc -> IO ()
212 dumpIf_core cond dflags dflag hdr doc
213   | cond
214     || verbosity dflags >= 4
215     || dopt Opt_D_verbose_core2core dflags
216   = dumpSDoc dflags dflag hdr doc
217
218   | otherwise = return ()
219
220 dumpIfSet_core :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
221 dumpIfSet_core dflags flag hdr doc
222   = dumpIf_core (dopt flag dflags) dflags flag hdr doc
223
224 dumpIfSet_dyn :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
225 dumpIfSet_dyn dflags flag hdr doc
226   | dopt flag dflags || verbosity dflags >= 4 
227   = dumpSDoc dflags flag hdr doc
228   | otherwise
229   = return ()
230
231 dumpIfSet_dyn_or :: DynFlags -> [DynFlag] -> String -> SDoc -> IO ()
232 dumpIfSet_dyn_or dflags flags hdr doc
233   | or [dopt flag dflags | flag <- flags]
234   || verbosity dflags >= 4 
235   = printDump (mkDumpDoc hdr doc)
236   | otherwise = return ()
237
238 mkDumpDoc :: String -> SDoc -> SDoc
239 mkDumpDoc hdr doc 
240    = vcat [text "", 
241            line <+> text hdr <+> line,
242            doc,
243            text ""]
244      where 
245         line = text (replicate 20 '=')
246
247
248 -- | Write out a dump.
249 --      If --dump-to-file is set then this goes to a file.
250 --      otherwise emit to stdout.
251 dumpSDoc :: DynFlags -> DynFlag -> String -> SDoc -> IO ()
252 dumpSDoc dflags dflag hdr doc
253  = do   let mFile       = chooseDumpFile dflags dflag
254         case mFile of
255                 -- write the dump to a file
256                 --      don't add the header in this case, we can see what kind
257                 --      of dump it is from the filename.
258                 Just fileName
259                  -> do  handle  <- openFile fileName AppendMode
260                         hPrintDump handle doc
261                         hClose handle
262
263                 -- write the dump to stdout
264                 Nothing
265                  -> do  printDump (mkDumpDoc hdr doc)
266
267
268 -- | Choose where to put a dump file based on DynFlags
269 --
270 chooseDumpFile :: DynFlags -> DynFlag -> Maybe String
271 chooseDumpFile dflags dflag
272
273         -- dump file location is being forced
274         --      by the --ddump-file-prefix flag.
275         | dumpToFile
276         , Just prefix   <- dumpPrefixForce dflags
277         = Just $ prefix ++ (beautifyDumpName dflag)
278
279         -- dump file location chosen by DriverPipeline.runPipeline
280         | dumpToFile
281         , Just prefix   <- dumpPrefix dflags
282         = Just $ prefix ++ (beautifyDumpName dflag)
283
284         -- we haven't got a place to put a dump file.
285         | otherwise
286         = Nothing
287
288         where   dumpToFile = dopt Opt_DumpToFile dflags
289
290
291 -- | Build a nice file name from name of a DynFlag constructor
292 beautifyDumpName :: DynFlag -> String
293 beautifyDumpName dflag
294  = let  str     = show dflag
295         cut     = if isPrefixOf "Opt_D_" str
296                          then drop 6 str
297                          else str
298         dash    = map   (\c -> case c of
299                                 '_'     -> '-'
300                                 _       -> c)
301                         cut
302    in   dash
303
304
305 -- -----------------------------------------------------------------------------
306 -- Outputting messages from the compiler
307
308 -- We want all messages to go through one place, so that we can
309 -- redirect them if necessary.  For example, when GHC is used as a
310 -- library we might want to catch all messages that GHC tries to
311 -- output and do something else with them.
312
313 ifVerbose :: DynFlags -> Int -> IO () -> IO ()
314 ifVerbose dflags val act
315   | verbosity dflags >= val = act
316   | otherwise               = return ()
317
318 putMsg :: DynFlags -> Message -> IO ()
319 putMsg dflags msg = log_action dflags SevInfo noSrcSpan defaultUserStyle msg
320
321 errorMsg :: DynFlags -> Message -> IO ()
322 errorMsg dflags msg = log_action dflags SevError noSrcSpan defaultErrStyle msg
323
324 fatalErrorMsg :: DynFlags -> Message -> IO ()
325 fatalErrorMsg dflags msg = log_action dflags SevFatal noSrcSpan defaultErrStyle msg
326
327 compilationProgressMsg :: DynFlags -> String -> IO ()
328 compilationProgressMsg dflags msg
329   = ifVerbose dflags 1 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text msg))
330
331 showPass :: DynFlags -> String -> IO ()
332 showPass dflags what 
333   = ifVerbose dflags 2 (log_action dflags SevInfo noSrcSpan defaultUserStyle (text "***" <+> text what <> colon))
334
335 debugTraceMsg :: DynFlags -> Int -> Message -> IO ()
336 debugTraceMsg dflags val msg
337   = ifVerbose dflags val (log_action dflags SevInfo noSrcSpan defaultDumpStyle msg)
338
339 \end{code}